我遇到了一些看起来像这样的代码:
export function foo(arg: string): arg is MyType {
return ...
}
我无法在文档或谷歌中搜索到 is
,这是一个很常见的词,基本上每个页面都会出现。
关键字在该上下文中的作用是什么?
最佳答案
参见 user-defined type guard functions 的引用资料获取更多信息。
function isString(test: any): test is string{
return typeof test === "string";
}
function example(foo: any){
if(isString(foo)){
console.log("it is a string" + foo);
console.log(foo.length); // string function
}
}
example("hello world");
在 isString()
之后,在上述格式中使用类型谓词 test is string
(而不是仅仅使用 boolean
作为返回类型) > 被调用时,如果该函数返回 true
,TypeScript 会将类型缩小为 string
在任何由函数调用保护的 block 中。
编译器会认为 foo
是 below-guarded block 中的 string
(并且仅在 below-guarded block 中)
{
console.log("it is a string" + foo);
console.log(foo.length); // string function
}
类型谓词仅在编译时使用。生成的 .js
文件(运行时)将没有区别,因为它不考虑 TYPE。
我将通过以下四个示例来说明差异。
例如 1: 上面的示例代码不会有编译错误和运行时错误。
例如 2:
下面的示例代码将出现编译错误(以及运行时错误),因为 TypeScript 已将类型缩小为 string
并检查 toExponential
不属于 字符串
方法。
function example(foo: any){
if(isString(foo)){
console.log("it is a string" + foo);
console.log(foo.length);
console.log(foo.toExponential(2));
}
}
例如3:
下面的示例代码没有编译错误,但会出现运行时错误,因为 TypeScript 只会在 protected block 中将类型缩小为 string
而不是之后,因此 foo.toExponential
不会产生编译错误(TypeScript 不认为它是 string
类型)。但是在运行时,string
没有toExponential
方法,所以会出现运行时错误。
function example(foo: any){
if(isString(foo)){
console.log("it is a string" + foo);
console.log(foo.length);
}
console.log(foo.toExponential(2));
}
例如4:
如果我们不使用 test is string
(类型谓词),TypeScript 将不会缩小 protected block 中的类型,下面的示例代码不会出现编译错误,但会出现运行时错误。
function isString(test: any): boolean{
return typeof test === "string";
}
function example(foo: any){
if(isString(foo)){
console.log("it is a string" + foo);
console.log(foo.length);
console.log(foo.toExponential(2));
}
}
结论是 test is string
(type predicate) 在编译时用来告诉开发者代码将有机会出现运行时错误。对于 javascript,开发人员不会知道编译时的错误。这是使用 TypeScript 的优势。
关于typescript - `is` 关键字在 typescript 中有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40081332/