打字稿为接口分配空值

时间:2020-06-25 13:32:33

标签: typescript interface

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

以下是我的意思的示例:

interface IMyInterface {
    field: any;
}

let test:IMyInterface = null; // <-- Compiler error: Type 'null' is not assignable to type 'IMyInterface'

2 个答案:

答案 0 :(得分:0)

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

通过@Guy Incognito:

let test:IMyInterface | null = null;

答案 1 :(得分:0)

启用compiler setting strictNullChecks(也包含在strict设置中)会从每种类型中删除nullundefined,因此要求将它们明确声明。 TypeScript handbook on Nullable types

没有strictNullChecks

declare let implicitlyNullable: number;

implicitlyNullable = 42;        //OK
implicitlyNullable = null;      //OK
implicitlyNullable = undefined; //OK

Playground Link

使用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

Playground Link


本质上,编译器选项与将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>;

Playground Link