File tree 1 file changed +26
-14
lines changed
1 file changed +26
-14
lines changed Original file line number Diff line number Diff line change @@ -677,28 +677,40 @@ let func:StringOrNumberFunc = fn;
677
677
678
678
### strictNullChecks
679
679
680
- ` strictNullChecks ` 设置对 ` null ` 和 ` undefined ` 进行严格类型检查。如果打开 ` strict ` 属性,这一项就会自动设为 ` true ` ,否则为 ` false ` 。
680
+ 不打开 ` strictNullChecks ` 的情况下,变量可以设为 ` undefined ` 或 ` null ` ,而不管其类型是什么 。
681
681
682
- ``` bash
683
- let value:string;
682
+ ``` typescript
683
+ // 不打开 strictNullChecks 的情况
684
+ let x: number ;
684
685
685
- // strictNullChecks:false
686
- // 下面语句不报错
687
- value = null;
686
+ x = undefined ; // 不报错
687
+ x = null ; // 不报错
688
688
```
689
689
690
- 它可以理解成只要打开,就需要显式检查` null ` 或` undefined ` 。
690
+ 上面示例中,变量` x ` 的类型是` number ` ,但是赋值为` undefined ` 或` null ` 都不会报错。这是为了继承 JavaScript 的设定:当变量没有赋值时,它的值就为` undefined ` 。
691
+
692
+ 一旦打开` strictNullChecks ` ,就相当于从变量的值里面,排除了` undefined ` 和` null ` ,除非变量的类型是这两种类型。
691
693
692
694
``` typescript
693
- function doSomething(x : string | null ) {
694
- if (x === null ) {
695
- // do nothing
696
- } else {
697
- console .log (" Hello, " + x .toUpperCase ());
698
- }
699
- }
695
+ // 打开 strictNullChecks 的情况
696
+ let x: number ;
697
+
698
+ x = undefined ; // 报错
699
+ x = null ; // 报错
700
700
```
701
701
702
+ 下面是一个例子。
703
+
704
+ ``` typescript
705
+ // 打开 strickNullChecks 时,类型 A 为 number
706
+ // 不打开时,类型 A 为 string
707
+ type A = unknown extends {} ? string : number ;
708
+ ```
709
+
710
+ 上面示例中,` {} ` 代表了 Object 类型,不打开` strictNullChecks ` 时,它包括了` undefined ` 和` null ` ,就相当于包括了所有类型的值,所以这时` unknown ` 类型可以赋值给` {} ` 类型,类型` A ` 就为` number ` 。打开` strictNullChecks ` 时,` {} ` 就排除掉了` undefined ` 和` null ` ,这时` unknown ` 类型就不能赋值给` {} ` 类型后,类型` A ` 就为` string ` 。
711
+
712
+ 另外,` strict ` 属性包含了` strictNullChecks ` ,如果打开` strict ` 属性,就相当于打开了` strictNullChecks ` 。
713
+
702
714
### strictPropertyInitialization
703
715
704
716
` strictPropertyInitialization ` 设置类的实例属性都必须初始化,包括以下几种情况。
You can’t perform that action at this time.
0 commit comments