Search code examples
typescripttypesnullnullable

Typescript - assign null to variable


I have a class like this:

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


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

unfortunately this will not compile anymore, until some previous version didn't give problems, now in the compilation phase I get the following error:

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

for the structure of my code it is important to make those properties "null" and reassign them later, how can I remedy the compiler's complaints?


Solution

  • type Nullable<T> = T | null
    export class Signal {
        method: Nullable<(d: any) => void> = null;
    
        public resetMethods(): void {
            this.method = null;
        }
    }
    

    Create custom type Nullable, very useful

    playground