[英]The keyword “is” in the return type of TypeScript function
In VSCode's source file, there are some functions with a particular return type specification, like this: 在VSCode的源文件中,有一些具有特定返回类型规范的函数,如下所示:
export function isString(str: any): str is string {
if (typeof (str) === _typeof.string || str instanceof String) {
return true;
}
return false;
}
So I wonder what is the purpose of "str is string" instead of just writing "boolean". 所以我想知道“str is string”的目的是什么,而不仅仅是写“boolean”。
Can we use "str is string" and the like in any other circumstances? 我们可以在任何其他情况下使用“str is string”等吗?
That is called User-Defined Type Guards . 这称为用户定义类型保护 。
Regular type guards let you do this: 常规型护卫让你这样做:
function fn(obj: string | number) {
if (typeof obj === "string") {
console.log(obj.length); // obj is string here
} else {
console.log(obj); // obj is number here
}
}
So you can use typeof
or instanceof
, but what about interfaces like this: 所以你可以使用
typeof
或instanceof
,但是这样的接口呢:
interface Point2D {
x: number;
y: number;
}
interface Point3D extends Point2D {
z: number;
}
function isPoint2D(obj: any): obj is Point2D {
return obj && typeof obj.x === "number" && typeof obj.y === "number";
}
function isPoint3D(obj: any): obj is Point2D {
return isPoint2D(obj) && typeof (obj as any).z === "number";
}
function fn(point: Point2D | Point3D) {
if (isPoint2D(point)) {
// point is Point2D
} else {
// point is Point3D
}
}
( code in playground ) ( 游乐场代码 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.