Skip to content

Instantly share code, notes, and snippets.

@abigmiu
Last active November 27, 2022 08:02
Show Gist options
  • Save abigmiu/680d6d4195bd58e216ef20d312d72940 to your computer and use it in GitHub Desktop.
Save abigmiu/680d6d4195bd58e216ef20d312d72940 to your computer and use it in GitHub Desktop.
typescript is 类型保护
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
        // 如下代码编译时会出错,运行时也会出错,因为 foo 是 string 不存在toExponential方法
        console.log(foo.toExponential(2));
    }
    // 编译不会出错,但是运行时出错
    console.log(foo.toExponential(2));
}
example("hello world");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment