Typescript 中 “?” 和 “!”
基础类型原始类型:number,string,boolean,symbol,null或undefinedobject表示非原始类型,使用object类型,就可以更好的表示像Object.create这样的APInull 和 undefined默认情况下,null和undefined是所有类型的子类型。 就是说你可以把 null和undefined赋值给number或者string类型的变量。str
·
基础类型
- 原始类型: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)