3

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?

3 Answers 3

3
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

Sign up to request clarification or add additional context in comments.

2 Comments

The other answers were also doable but i loved this one!! TNX
Nullable<T> is more general, nice one.
2

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;
    }
}

4 Comments

mmmmmm (d: any) => void) | null; so it wouldn't be like saying that the return type of the method is void or null ??
@T.J.Crowder: Without ? typescript still complains because the fields don't have an initial value. If they do get a value in the constructor but it's left out in this example, then it's not needed.
@Plastic: No, because of the parenthesis.
Yeah, I was assuming the constructor definitely assigns it. :-)
1

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

1 Comment

method: MyMethod | null; was the cleanest way for me. Got to keep it simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.