typescript - 打字稿变量类型规范
问题描述
我有一个变量可能是类型A或类型B的情况。然后使用If
我知道变量是什么类型并应用适当的响应。
我得到了 TSLINT 错误。
function checkIfItsAString(foo: String | Number): boolean {
return foo instanceof String;
}
function example2(foo: String | Number) {
if (checkIfItsAString(foo)) {
foo.charAt(5);
return;
}
}
我怎么能对打字稿说,
从现在开始,这个变量的类型是“String”
解决方案
您可以使用类型谓词让编译器自动缩小类型范围。您的谓词已经起作用,要使其成为类型谓词,您只需说出它对值的含义:
function checkIfItsAString(foo: String | Number): foo is String {
// tell the compiler true means it's a string -> ^^^^^^^^^^^^^
return foo instanceof String;
}
这使编译器可以自动确定类型:
function example2(foo: String | Number) {
if (checkIfItsAString(foo)) { //foo is a String
foo.charAt(5);
return;
}
foo.toFixed(""); //foo is a Number
}
或者,您可以in
直接使用运算符,该运算符将从类型列表中进行类型消除:
function example2(foo: String | Number) {
if ("charAt" in foo) {
// ^^^^^^ this only exists on String not on Number, so it's a String
foo.charAt(5);
return;
}
foo.toFixed(2); //a number, since it doesn't have "charAt"
}
这对于一次性更简单的检查更有用,因此您不需要整个谓词来处理它。如果这是一个用例,它可以用来缩小类型。这是一个人为的示例,用于in
在几个步骤中消除类型。
/*
* ake a Nnumber, String, array of Numbers, or the HTMLCollection array-like:
* for Number - the value
* for HTMLCollection - the length
* for array of number - the sum + the length
* for string - the length + the trimmed length
*/
function dummyExample(x : Number | String | Number[] | HTMLCollection) : number {
if ("length" in x) { // String | Number[] | HTMLCollection
let totalLength: number = x.length;
if ("slice" in x) { // String | Number[]
if ("reduce" in x) { // Number[]
return x.reduce((a: number, b: Number) => a + b.valueOf(), 0) + length;
} else { // String
return x.trim().length + totalLength;
}
} else { // HTMLCollection
return totalLength;
}
} else { // Number
return x.valueOf();
}
}
推荐阅读
- react-native - 我可以将 Web 应用程序的组件与 React Native 应用程序一起使用吗
- scala - Scala案例类中的隐式与隐式val
- java - 如何让 ViewModel 在首次运行时显示网络数据
- r - R中从长到宽到长格式的困难
- scala - Apache spark内部连接2个数据框得到TreeNodeException
- r - 渲染函数返回的标签字符串
- javascript - 将另一个类的静态方法分配给原型
- r - For 循环工作得很好,但是一旦我用它做一个函数,它突然不会在 R 中给出正确的结果
- python - Elasticsearch [5.6] Sum Aggregations 失去精度?
- git - 是否有可能在合并之前获得合并提交的哈希?