1

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?

Plastic
  • 9,874
  • 6
  • 32
  • 53

3 Answers3

2
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

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
1

As the code is right now, you have to declare the fields as optional anyway, since they are not assigned a value. And it that case you could assign undefined to make TS happy:

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


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

If you really want/need to assign null, then you can use a union type:

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


    public resetMethods(): void {
        this.method = null;
        this.otherMethod = null;
    }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Define a type for your "methods":

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

Then either declare them with that | null:

method: MyMethod | null;

Or give yourself a convenience type:

type NullableMyMethod = MyMethod | null;

and use that

method: NullableMyMethod;

On the playground

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875