philkunz
philkunz

Reputation: 461

TypeScript conditional types not compiling

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

Answers (1)

cheesyMan
cheesyMan

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[].

enter image description here

enter image description here

## EDIT / ADD ##

I added a link to this playground in the comments

enter image description here

enter image description here

Upvotes: 1

Related Questions