(I am implementing strict null checks)
The arrow function I have includes overloaded types:
type INumberConverter = {
(value: number): number;
(value: null): null;
};
const decimalToPercent: INumberConverter = (value: number | null): number | null => {
if (!value) {
return null;
}
return value * 100;
};
Based on my research from various sources (Can I use TypeScript overloads when using fat arrow syntax for class methods?), this code should be valid. However, I encounter the following error message:
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 define this function conventionally (using 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;
}
This approach works without any errors.
I must utilize an arrow function to maintain the context of this
, and I require overloading so that TypeScript understands that decimalToPercent(1)
cannot be null.
Why is it not working as intended in my initial implementation, and how can I resolve this issue?