Ron*_*ong 4 function typescript
在VSCode的源文件中,有一些具有特定返回类型规范的函数,如下所示:
export function isString(str: any): str is string {
if (typeof (str) === _typeof.string || str instanceof String) {
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
所以我想知道"str is string"的目的是什么,而不仅仅是写"boolean".
我们可以在任何其他情况下使用"str is string"等吗?
这被称为用户定义类型保护.
常规型护卫让你这样做:
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
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可以使用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
}
}
Run Code Online (Sandbox Code Playgroud)
(游乐场代码)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |