0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

7 Comments

Ah, I see. ... Is there a way to solve this then without function overloads? I want the inputArg to be only of type string or string[] and the output type to be the same as inputArg when using the function.
@philkunz You can use a generic to 'carry' the input type to the return type: const myFunction = <T extends string | string[]>(inputArg: T): T { ... }. See working example
Whats strange though, that this doesn't work then: typescriptlang.org/play?#code/…
@cheesyMan See, type inference still doesn't work. The assigned variables still are of type string | string[], regardless of the input. typescriptlang.org/play?#code/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.