当打开 —strictNullChecks 配置:当你声明任何一个类型,都默认不包括 null
或 undefined
,但你可以明确声明一个联合类型:
let exampleString = "foo";
exampleString = null;
// Type 'null' is not assignable to type 'string'.
let stringOrNull: string | null = "bar";
stringOrNull = null;
stringOrNull = undefined;
// Type 'undefined' is not assignable to type 'string | null'.
可选链:
let x = foo?.bar.baz();
// 等价于
let x = foo === null || foo === undefined ? undefined : foo.bar.baz();
非空断言:
语雀内容