I am trying to type a function that should return an array type, if the input parameter is array type, and a normal parameter otherwise. Here's my attempt:
function test<T extends number|number[]>(a: T):T extends number[] ? string[] : string {
if (Array.isArray(a)) {
return ['123', '45']
}
return '123'
}
I get an error at the return statements: Type 'string' is not assignable to type 'T extends number[] ? string[] : string'.
What I'm looking for is the following:
const a = test(3) // "a" is string type
const b = test([1,2,3]) // "b" is string[] type