2016-12-01 120 views
4

在VSCode的源文件,有與特定的返回類型規範的一些功能,像這樣:關鍵字「是」以打字稿函數的返回類型

export function isString(str: any): str is string { 
    if (typeof (str) === _typeof.string || str instanceof String) { 
    return true; 
    } 

    return false; 
} 

所以我不知道什麼是「的宗旨str是字符串「而不是隻寫」boolean「。

我們可以在任何其他情況下使用「str是字符串」嗎?

回答

5

這就是所謂的User-Defined Type Guards

普通型後衛讓你這樣做:

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 
    } 
} 

所以,你可以使用typeofinstanceof,但對於這樣的接口:

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