这可能是一个愚蠢的问题,但是我不知道如何为声明为接口类型的变量设置null
的值。
以下是我的意思的示例:
interface IMyInterface {
field: any;
}
let test:IMyInterface = null; // <-- Compiler error: Type 'null' is not assignable to type 'IMyInterface'
答案 0 :(得分:0)
要么将其定义为联合类型,要么在strictNullChecks
下的ts-config中将compilerOptions
标志设置为false。
通过@Guy Incognito:
let test:IMyInterface | null = null;
答案 1 :(得分:0)
启用compiler setting strictNullChecks
(也包含在strict
设置中)会从每种类型中删除null
和undefined
,因此要求将它们明确声明。 TypeScript handbook on Nullable types。
没有strictNullChecks
:
declare let implicitlyNullable: number;
implicitlyNullable = 42; //OK
implicitlyNullable = null; //OK
implicitlyNullable = undefined; //OK
使用strictNullChecks
:
declare let implicitlyNullable: number;
implicitlyNullable = 42; //OK
implicitlyNullable = null; //error
implicitlyNullable = undefined; //error
///////////////////////////////////////
declare let explicitlyNullable: number | null;
explicitlyNullable = 42; //OK
explicitlyNullable = null; //OK
explicitlyNullable = undefined; //error
///////////////////////////////////////
declare let explicitlyUndefinable: number | undefined;
explicitlyUndefinable = 42; //OK
explicitlyUndefinable = null; //error
explicitlyUndefinable = undefined; //OK
///////////////////////////////////////
//nilable = can be both undefined and null
declare let explicitlyNilable: number | undefined | null;
explicitlyNilable = 42; //OK
explicitlyNilable = null; //OK
explicitlyNilable = undefined; //OK
本质上,编译器选项与将NonNullable
utility type自动应用于现有的每种类型非常相似。因此,如果没有strictNullChecks
,则您不接受“空”值是中的opt- 。
就我自己而言,我更喜欢strictNullChecks
的准确性。它使编写代码和进行代码推理变得更加容易,而不必到处散布if(someVar)
,因为您不知道有人会传入什么。即使没有简单的空检查,即使是简单的函数也可能会成为问题:
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3)); //strictNullChecks: false -> 5
//strictNullChecks: true -> 5
console.log(add(2, null)); //strictNullChecks: false -> 2
//strictNullChecks: true -> compiler error
console.log(add(2, undefined)); //strictNullChecks: false -> NaN
//strictNullChecks: true -> compiler error
Playground Link - strictNullChecks: false
Playground Link - strictNullChecks: true
为方便起见,您可以创建一些处理不同类型的可空性的通用类型:
type Nullable<T> = T | null;
type Undefinable<T> = T | undefined;
type Nilable<T> = Nullable<Undefinable<T>>
declare let implicitlyNullable: number;
declare let explicitlyNullable: Nullable<number>;
declare let explicitlyUndefinable: Undefinable<number>;
declare let explicitlyNilable: Nilable<number>;