• home > webfront > ECMAS > typescript >

    TS2322:Type null/undefined is not assignable to type T error

    Author:zhoulujun Date:

    solve the "Type null is not assignable to type " error in TypeScript。let name:string = person name!;let name:string = person name || ; tsconfig :strictNullChecks

    今天遇到 

    TS2322: Type 'null' is not assignable to type string,

    TS2322: Type 'undefined' is not assignable to type 'number' .ts

    看到

    具体问题:


    Use a union type to solve the "Type 'null' is not assignable to type" error in TypeScript, e.g. name: string | null. The type of the specific value has to accept null, because if it doesn't and you have strictNullChecks enabled in tsconfig.json, the type checker throws the error.

    当然不止null,undefined也会有同样的问题

    出现这种问题的情况:

    一般情况如下

    let b:Record<string, any> = {}
    let c:string = b['m']
    let d:string = null

    这个可以用联合类型解决

    函数可选值

    function m(a,b?){
        let x:string = b
    }


    这个可以用默认值取代可选值


    以上两种都是代码层面解决,总结就是

    解决办法就是:

    • 设置联合类型,或给定默认值。

    • 配置tsconfig,strictNullChecks 为false

    • 告诉TS 值不为null :

      • let name:string = person.name!

      • let name:string = person.name || '';

    还有其他方案吗?




    转载本站文章《TS2322:Type null/undefined is not assignable to type T error》,
    请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/typescript/2022_0615_8839.html