美文网首页
(ts-04)ts类型断言使用

(ts-04)ts类型断言使用

作者: 一懿一 | 来源:发表于2021-08-31 14:33 被阅读0次

    类型断言就是我们自己确认了类型,告诉编译器当前类型是什么

    经常在开发时遇到某字段明明知道类型,却无法使用该类型的方法,例如string类型的length,例如下面的情况:

    function foo (key: string | null) {
        const now = key;
        console.log(now.length); // 因为now可能为null,所以此时length可能不存在,编译不通过
        
        const now1 = key;
        console.log((now1 as string).length); // 因为通过类型推断出now1为string,所以length属性存在,编译通过
        console.log((<string>now1).length); // 第二种写法,JSX不支持
    }
    

    相关文章

      网友评论

          本文标题:(ts-04)ts类型断言使用

          本文链接:https://www.haomeiwen.com/subject/dajziltx.html