TypeScript function type assignment

Viewed 37

Consider the following

interface ITest {
    someMethod(a: any): void;
}
const someImplementation = (a) => { return Promise.resolve(); }
const anotherImplementation = (a, b) => { return Promise.resolve(); }

//No error emitted when assigning (a: any) => Promise<void> to (a: any): void
let test1: ITest = { someMethod: someImplementation }; 

// No error emitted when assinging () => Promise<void> to (a: any): void
let test2: ITest = { someMethod: () => someImplementation(1) };

//No error emitted when assigning (a: any) => Promise<void> to (a: any): void
let test3: ITest = { someMethod: (a) => someImplementation(1) };

//Error emitted when assigning (a: any, b: any) => Promise<void> to (a: any): void
//ERROR: Type 'Promise<void>' is not assignable to type 'void'.
let test4: ITest = { someMethod: (a, b) => someImplementation(1) };

//DIFFERENT error emitted when assigning (a: any, b: any) => Promise<void> to (a: any): void
//ERROR: Type '(a: any, b: any) => Promise<void>' is not assignable to type '(a: any) => void'.
let test5: ITest = { someMethod: anotherImplementation };

Playground

Why do the test1, test2, and test3 assignments not produce errors about void to Promist<void> assignment while the test4 assignment does? Also, why would the test4 and test5 assignments give different errors? Is there any implicit assertion going on for void --> Promise<void> ?

1 Answers

The number of arguments matter. For the first three tests, the arguments are accepted. Even for empty arguments, if your TS is not that strict it will not complain. It is still valid javascript because an empty argument is undefined, and undefined is considered any.

test4: someMethod expects a return void, but the function you're passing in returns a promise, fix test4 by making someMethod(a:any) : Promise<void>

test5: same issue as test4, but also paramater needs to match the type someMethod. fix test4 by making someMethod(a:any, b?:any) : Promise<void>

General fix:

interface ITest {
    someMethod(a: any, b?: any): Promise<void> | void;
}
Related