Skip to content

Commit e7e1a77

Browse files
committedOct 3, 2024
docs(tsconfig.json): edit strictNullChecks
1 parent 5c56fd5 commit e7e1a77

File tree

1 file changed

+26
-14
lines changed

1 file changed

+26
-14
lines changed
 

‎docs/tsconfig.json.md

+26-14
Original file line numberDiff line numberDiff line change
@@ -677,28 +677,40 @@ let func:StringOrNumberFunc = fn;
677677

678678
### strictNullChecks
679679

680-
`strictNullChecks`设置对`null``undefined`进行严格类型检查。如果打开`strict`属性,这一项就会自动设为`true`,否则为`false`
680+
不打开`strictNullChecks`的情况下,变量可以设为`undefined``null`,而不管其类型是什么
681681

682-
```bash
683-
let value:string;
682+
```typescript
683+
// 不打开 strictNullChecks 的情况
684+
let x:number;
684685

685-
// strictNullChecks:false
686-
// 下面语句不报错
687-
value = null;
686+
x = undefined; // 不报错
687+
x = null; // 不报错
688688
```
689689

690-
它可以理解成只要打开,就需要显式检查`null``undefined`
690+
上面示例中,变量`x`的类型是`number`,但是赋值为`undefined``null`都不会报错。这是为了继承 JavaScript 的设定:当变量没有赋值时,它的值就为`undefined`
691+
692+
一旦打开`strictNullChecks`,就相当于从变量的值里面,排除了`undefined``null`,除非变量的类型是这两种类型。
691693

692694
```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; // 报错
700700
```
701701

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+
702714
### strictPropertyInitialization
703715

704716
`strictPropertyInitialization`设置类的实例属性都必须初始化,包括以下几种情况。

0 commit comments

Comments
 (0)