33

I understand the error message:

Type '() => void' is not assignable to type '() => {}'

Well sort of, it is telling me there is a type casting issue. However I can't work out why the compiler thinks the types are not the same.

The back ground to the code is that I have a typescript class that is given a function and then stores it as a member. I want to be able to initialise the member with an empty 'noop' function so that it don't have to null check it before use.

I have managed to reduce problem down to the following example test code:

export class Test {
    private _noop: () => {};

    constructor(
    ) {
        this._noop = () => { };     //I guess the compiler thinks this is returning in a new empty object using the json syntax
        this._noop = this.noop;     //I would have thought this shoud definitely work
        this._noop = () => undefined;   //This does works
    }

    public noop(): void {
        //Nothing to see here...
    }
}

The three statements in the constructor are all intended to do the same job: initialise the member with a no operation function. However only the last statement works:

this._noop = () => undefined; 

The other two statements produce the compile error.

Does any one know why the compiler can't seem to match the types?

Tom Maher
  • 1,914
  • 2
  • 23
  • 39

2 Answers2

25

In your definition private _noop: () => {}; _noop is typed as a function returning an object.

When you assign it as this._noop = () => { }; the function you are trying to assign to _noop is of type () => void.

If you wanted _noop to be function returning nothing then type it as:

private _noop: () => void;
Saravana
  • 37,852
  • 18
  • 100
  • 108
8

The below definition means, _noop is a function must return an object (including undefined and null).

private _noop: () => {};

it's equal to:

private _noop: () => Object;

you can make all three statements work with:

private _noop: () => any;

or the first statement will work with both of these:

this._noop = () => ({});
this._noop = () => { return {} };
Val
  • 21,938
  • 10
  • 68
  • 86
  • Ah brilliant... that makes more sense. I hadn't realised that the member type was declared incorrectly. I thought I was declaring it as a void. Thank you for explaining that. My follow up question would've been how do you declare a type that is a function that returns void. However it looks like @Saravana has already done that. – Tom Maher Jul 28 '17 at 08:46