打字稿-将空值分配给变量

Typescript - assign null to variable

我有一个 class 这样的:

export class Signal {
    method: (d: any) => void;
    otherMethod: (d: any) => void;


    public resetMethods(): void {
        this.method = null;
        this.otherMethod = null;
    }
}

不幸的是,这将不再编译,直到一些以前的版本没有出现问题,现在在编译阶段我得到以下错误:

 Type 'null' is not assignable to type '(d: any) => void'.

对于我的代码结构,重要的是创建这些属性 "null" 并在以后重新分配它们,我该如何补救编译器的投诉?

由于代码是正确的,您必须将这些字段声明为可选的,因为它们没有被赋值。在这种情况下,您可以分配 undefined 让 TS 开心:

export class Signal {
    method?: (d: any) => void;
    //    ^
    otherMethod?: (d: any) => void;
    //         ^


    public resetMethods(): void {
        this.method = undefined;
        this.otherMethod = undefined;
    }
}

如果你真的want/need赋值null,那么你可以使用联合类型:

export class Signal {
    method?: ((d: any) => void) | null;
    otherMethod?: ((d: any) => void) | null;


    public resetMethods(): void {
        this.method = null;
        this.otherMethod = null;
    }
}

为您的 "methods" 定义一个类型:

type MyMethod = (d: any) => void;

然后用 | null:

声明它们
method: MyMethod | null;

或者给自己一个方便型:

type NullableMyMethod = MyMethod | null;

并使用它

method: NullableMyMethod;

On the playground

type Nullable<T> = T | null
export class Signal {
    method: Nullable<(d: any) => void> = null;

    public resetMethods(): void {
        this.method = null;
    }
}

创建自定义类型 Nullable,非常有用

playground