I am trying to type a function in TypeScript:
Here everything is OK
const myFunction_1 = (param1: number, param2: number): number => {
return param1 + param2;
};
const result_1 = myFunction_1(1, 2);
console.log(result_1);
Here an error shown, as nothing is returned: A function whose declared type is neither 'void' nor 'any' must return a value.
const myFunction_2 = (param1: number, param2: number): number => {};
const result_2 = myFunction_2(1, 2);
console.log(result_2);
Here everything is ok
type myFunction_3Type = (param1: number, param2: number) => number;
const myFunction_3: myFunction_3Type = (param1: number, param2: number) => {
return param1 + param2;
};
const result_3 = myFunction_3(1, 2);
And here is the interesting part. I declare two interfaces: one for the input of the function and another for the output. I use them in the type myFunction_4Type
; Then I use this type in the function, and I force the function to return an object that doesn't match the output interface; but it doesn't display an error!
interface IMyFunctionInput {
a: number;
b: number;
}
interface IMyFunctionOutput {
a: number;
b: number;
}
type myFunction_4Type = (payload: IMyFunctionInput) => IMyFunctionOutput;
const myFunction_4: myFunction_4Type = payload => {
return {
a: 1,
b: 2,
c: 3 // This key and prop should cause an error, as it doesn't match the interface IMyFunctionOutput
};
};
const payload = {
a: 1,
b: 2
};
const result_4 = myFunction_4(payload);
Any help will be welcome : )