Typescript 中 “?” 和 “!”

基础类型

  • 原始类型:number,string,boolean,symbol,null或undefined
  • object表示非原始类型,使用object类型,就可以更好的表示像Object.create这样的API

null 和 undefined

  • 默认情况下,null和undefined是所有类型的子类型。 就是说你可以把 null和undefined赋值给number或者string类型的变量。

strictNullChecks

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    // "strictNullChecks": true,                    /* Enable strict null checks. */
  }
}
  • false
// 当strictNullChecks置为false,或者默认。ts编译器不进行null和undefined的严格检查

let str1: string = undefined;//success

let str2: string = null;//success
  • true
//当strictNullChecks置为true,null和undefined只能赋值给void和它们各自

let str1: string = undefined;//fail Type 'undefined' is not assignable to type 'string'.

let str2: string = null;//fail Type 'null' is not assignable to type 'string'.

可选属性 ?

  • 【?】 表示在strictNullChecks置为true时,height?: number; 等价于 height: number | undefined;
interface Test {
  height?: number;
  width: number;
}

function testfunc(test: Test) {
  test.height = undefined;// success
  test.width = undefined;// fail Type 'undefined' is not assignable to type 'number'.
}

非空断言操作符 !

  • strictNullChecks置为true时,类中的成员必须明确定义类型;【!】表示在此处告诉编译器,此成员不会为null,不会为undefined;
class Test1 {
  height!: number; //success 非null 非 undefined类型

  test() {
    this.height = null;// fail Type 'null' is not assignable to type 'number'.
    this.height = undefined;// fail Type 'undefined' is not assignable to type 'number'.
  }
}


class Test2 {
 height: number | undefined | null;//success 可null 可undefined类型
}


参考

https://www.typescriptlang.org/tsconfig#strictNullChecks
https://www.tslang.cn/docs/handbook/classes.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值