Reputation: 461
Why does the following typescript not compile without errors?
const conditionalTypedFunction =
(inputArg: string | string []):
typeof inputArg extends string ? string : string[]
=> {
return inputArg;
}
Here is a link to the TypeScript Playground: https://www.typescriptlang.org/play?ssl=3&ssc=2&pln=1&pc=1#code/MYewdgzgLgBKYBMCWUngIYBsAqBPADgKYIBiArmMKuDALwwAUSY+ZUAggE4DmAXDNE7NuMAD4CoQsCIDaAXQCU-KAUIgAZjGasOPGIQAeUQoggSpIgPznhMfoOHy6APhgBvALAAoGL5idCKDJOMC0WNi5uAG5vAF9vIA
I know that function overloads are an option. But I don't want to use them here.
Upvotes: 0
Views: 101
Reputation: 1510
As inputArg
is an Union Type string | string []
, the condition typeof inputArg extends string
always yields false.
So, to TypeScript the function is always supposed to return a string[]
.
## EDIT / ADD ##
I added a link to this playground in the comments
Upvotes: 1