Typescript 将 null 分配给接口

zeb*_*zeb 6 interface typescript

这可能是一个愚蠢的问题,但我不知道如何设置声明null为接口类型的变量的值。

下面是我的意思的一个例子:

interface IMyInterface {
    field: any;
}

let test:IMyInterface = null; // <-- Compiler error: Type 'null' is not assignable to type 'IMyInterface'
Run Code Online (Sandbox Code Playgroud)

小智 9

要么将其定义为联合类型,要么strictNullChecks在 ts-config 下的 ts-config 中将标志设置为 false compilerOptions

作者:@Guy Incognito:

let test:IMyInterface | null = null;
Run Code Online (Sandbox Code Playgroud)


VLA*_*LAZ 6

启用编译器设置 strictNullChecks(也包含在设置中strict)会从每种类型中删除nullundefined,因此需要显式声明它们。关于 Nullable 类型的 TypeScript 手册

没有strictNullChecks

declare let implicitlyNullable: number;

implicitlyNullable = 42;        //OK
implicitlyNullable = null;      //OK
implicitlyNullable = undefined; //OK
Run Code Online (Sandbox Code Playgroud)

游乐场链接

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
Run Code Online (Sandbox Code Playgroud)

游乐场链接


NonNullable本质上,编译器选项与自动将实用程序类型应用于现有的每种类型非常相似。因此,如果strictNullChecks您不接受“空”值,则属于选择加入

就我自己而言,我更喜欢 的准确性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
Run Code Online (Sandbox Code Playgroud)

游乐场链接 -strictNullChecks: false

游乐场链接 -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>;
Run Code Online (Sandbox Code Playgroud)

游乐场链接