typescript中特殊符号(?/!)用法

1. 属性或参数中使用 ?:表示该属性或参数为可选项

2. 属性或参数中使用 !:表示强制解析(告诉typescript编译器,这里一定有值),常用于vue-decorator中的@Prop

3. 变量后使用 !:表示类型推断排除null、undefined

 

例如

   private _options!: ChatBoxMsgItemOptions;
    public get options(): ChatBoxMsgItemOptions {
        return this._options;
    }
 
  @property(Label)
    labelTitle!: Label;
 

基础类型

  • 原始类型: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类型
}

 

posted @ 2023-01-18 11:01  cslie  阅读(2694)  评论(0)    收藏  举报