I am trying to defined a basic interface with an arrow function as properties. However, it gives me a TS error.
interface InterfaceTest {
input?: (test: number | string) => number | undefined;
}
const myVariable: InterfaceTest = {
input: (test: number) => {
return test;
},
};
const myVariable2: InterfaceTest = {
input: (test: string) => {
return parseInt(test, 2);
},
};
TS2322: Type '(test: number) => undefined' is not assignable to type '(test: string | number) => number | undefined'. Types of parameters 'test' and 'test' are incompatible. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.
In fact, I do not understand the error because I would like to have a string or a number as parameter to my function and it tells me that I can not only number. How could I do to have string or number as input of my arrow function ?
In addition, when I do that the error disappear
interface InterfaceTest {
input?(test: number | string): number | undefined;
}
const myVariable: InterfaceTest = {
input: (test: number) => {
return test;
},
};
const myVariable2: InterfaceTest = {
input: (test: string) => {
return parseInt(test, 2);
},
};
Why ?
number | string
, but thenmyVariable
just specifiesnumber
. These two should match. – Evert