I'm going to present a couple of examples with and without generic return types and I'm confused as to why typescript doesn't treat all the examples the same.
Example 1: base case - function overload (works correctly)
function test(data:string):string
function test(data:string[]):string[]
function test(data:string | string[]): string | string[] {
if(Array.isArray(data)){
return ['']
}
return data
}
const testArr = test([]) // return type is Array
const testStr=test('a') // return type is string
Now I'm gonna try to do the same with a generic data type:
Example 2: inferred return types from the function are wrong
function testGeneric<T extends string | string[]>(data:T){
if(Array.isArray(data)){
return ['']
}
return data
}
const testArrGen = testGeneric([])
const testStrGen=testGeneric('a')
Example 3: The function itself has the return types wrong.
function testGeneric2<T extends string | string[]>(data:T): T extends string? T : T[]{
if(Array.isArray(data)){
return [''] // error
}
return data // error
}
const testArrGen2 = testGeneric2([]) // string[] || never[]
const testStrGen2=testGeneric2('a') // "a"| string[]
Now I would like to understand why examples 2 and 3 are wrong, and how could I create the correct implementation using generics.