Typescript 将 null 分配给类型不会触发错误

Whi*_*her 7 typescript angular

谁能解释一下为什么这段代码不会触发错误?

import { Injectable } from '@angular/core';

interface Animal{
  name: string;
}

@Injectable()
export class AnimalService {
  lion: Animal = null;
  constructor() {}
  get(){
   return this.lion;
 }
}
Run Code Online (Sandbox Code Playgroud)

Sar*_*ana 8

您必须"strictNullChecks": true对其进行设置tsconfig.json,以便在您这样做时抛出错误lion: Animal = null;

请参阅编译器标志的文档strictNullChecks

在严格的空检查模式下,空值和未定义值并不在每种类型的域中,并且只能分配给它们自己和任何(一个例外是未定义也可以分配给void)。

另请参阅:https ://ariya.io/2016/10/typescript-2-and-strict-null-checking