In the following code I defined the type of a function doSomething to be this type: (value: User) => User
Strangely when assigning a function with a wrong return type to doSomething then Typescript will not complain. Why is that?
interface User {
userName: string;
}
const test: User = {
userName: 'test',
bla: '123' // OK: TS complains
}
let doSomething: (value: User) => User;
doSomething = () => { // NOK: TS is not complaining about the missing parameter
return {
userName: 'test',
bla: '123' // NOK: Why does TS not complain?
}
};
Same thing happens when defining the type of a callback function and then pass a callback which returns a "wrong" value:
interface User {
userName: string;
}
class Test {
doSomething(callback: (value: User) => User): void {}
}
const test = new Test();
test.doSomething(() => { // NOK: TS is not complaining about the missing parameter
return {
userName: 'test',
bla: '123' // NOK: Why does TS not complain?
}
})
See example on stackblitz: https://stackblitz.com/edit/typescript-callback-2
forEach(callback: (element?: T, index?: number, array?: T[]))which explains that skipping parameters is perfectly fine.