类型保护功能

你可以使用你想要的任何逻辑声明用作类型保护的函数。

他们采取以下形式:

function functionName(variableName: any): variableName is DesiredType {
    // body that returns boolean
}

如果函数返回 true,则 TypeScript 会在调用函数的任何块中将类型缩小为 DesiredType

例如( 试一试 ):

function isString(test: any): test is string {
    return typeof test === "string";
}

function example(foo: any) {
    if (isString(foo)) {
        // foo is type as a string in this block
        console.log("it's a string: " + foo);
    } else {
        // foo is type any in this block
        console.log("don't know what this is! [" + foo + "]");
    }
}

example("hello world");          // prints "it's a string: hello world"
example({ something: "else" });  // prints "don't know what this is! [[object Object]]"

保护的函数类型谓词(函数返回类型位置中的 foo is Bar)在编译时用于缩小类型,函数体在运行时使用。类型谓词和函数必须一致,否则你的代码将无效。

类型保护功能不必使用 typeofinstanceof,它们可以使用更复杂的逻辑。

例如,此代码通过检查它的版本字符串来确定你是否有 jQuery 对象。

function isJQuery(foo): foo is JQuery {
    // test for jQuery's version string
    return foo.jquery !== undefined;
}

function example(foo) {
    if (isJQuery(foo)) {
        // foo is typed JQuery here
        foo.eq(0);
    }
}