(I'm using strict null checks)
I have the following arrow function, with overloaded type:
type INumberConverter = {
(value: number): number;
(value: null): null;
};
const decimalToPercent: INumberConverter = (value: number | null): number | null => {
if (!value) {
return null;
}
return value * 100;
};
To my understanding from other questions (Can I use TypeScript overloads when using fat arrow syntax for class methods?) this should be a valid. Never the less I get the following error:
TS2322: Type '(value: number | null) => number | null' is not assignable to type 'INumberConverter'. Type 'number | null' is not assignable to type 'number'. Type 'null' is not assignable to type 'number'
If I write this function regularly (with the function keyword):
function decimalToPercent(value: null): null;
function decimalToPercent(value: number): number;
function decimalToPercent(value: number | null): number | null {
if (!value) {
return null;
}
return value * 100;
}
It works without errors.
I need to use arrow function so this will not be change, and I need this overloading so typescript knows decimalToPercent(1) cannot be null.
Why doesn't it work the way I did it, and how can I fix it?