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