Here is simple synthetic function
function test(input) {
if (typeof input === 'number') {
return 'a'
} else {
return input
}
}
I want to type it but cannot figure out approach. The best I was able to get is:
function test<T extends Number>(input: T): string;
function test<T>(input: T): T;
function test(input) {
if (typeof input === 'number') {
return 'a'
} else {
return input
}
}
const a = [test('2'), test(2), test(null), test(true)] as const
// ^? a: readonly ['2', string, null, true]
// looks valid
const b = [test<string>('2'), test<boolean>(true)] as const
// ^? b: readonly [string, boolean]
// I can control/generalize types!
The blot on the landscape for that solution looks like that:
Parameter ‘input’ implicitly has an ‘any’ type.
What am I missing here? How to make Typescript happy while keeping types consistent and reliable?