美文网首页
安全导航运算符和非空断言

安全导航运算符和非空断言

作者: learninginto | 来源:发表于2020-12-22 19:19 被阅读0次
    • 安全导航运算符

    即使变量不存在时,也不报错。可以对属性出现null和undefined值进行保护,以防止视图渲染失败

    安全导航运算符是ES2020中的新语法,又叫可选链

    <p>The hero name is :{{Hero?.name}}</p>
    

    当item为null时,视图仍然渲染,显示的值为The hero name is :, 直到后面的name请求出来。

    • 非空断言

    在ts中,开启--strictNullChecks后,将一个可能是undefiendnull的变量赋给一个有确切类型的变量时,会报错;但在特定情况下,我们很确定那个变量一定不是undefinednull,此时可以用非空断言操作符

    用了这个操作符的变量,ts则不必再操心,这个变量一定是有值的。非空断言生效的前提是开启--strictNullChecks

    1. tsconfig.json中设置"strictNullChecks:true"
    2. tslint.json中设置"no-non-null-assertion:false"
    name : string | null = ''
    constructor(){
        //报错,this.name可能为null,所以不允许赋值给heroName
        const hreoName : string = this.name;
        
        //没毛病,因为告诉了ts,这里的this.name一定不是null
        const hreoName : string = this.name!;
        
        //以上写法相当于
        if(this.name){
            const heroName : string = this.name;
        }
    }
    
    • 类型转换函数 $any()

    有时候,绑定的表达式不能或很难指定类型。要消除这种报错,你可以使用 $any() 转换函数来把表达式转换成 any 类型

    假设无法确定item的类型,也就不能确定item是否有bestByDate,这时就会报错,可以用$any()item视为any类型,避免其报错

    <p>The item's undeclared best by date is: {{$any(item).bestByDate}}</p>
    

    也可以用这个函数绑定组件中不存在的变量

    <p>The item's undeclared best by date is: {{$any(this).bestByDate}}</p>
    

    相关文章

      网友评论

          本文标题:安全导航运算符和非空断言

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