Typescript: why does `let val: K extends K ? string : any = ""` not compile?

Viewed 154

Within the context where some parametric Type K exists, and it is clear that K extends string | number | symbol the line

let val: K extends K ? string : any = ""

Gives a compiler error:

TS2322: Type 'string' is not assignable to type 'K extends K ? string : any'.

I would have expected this to compile, since K extends K should evaluate to true.
generally, isn't true ? A : B always inferred to be A ? What's the problem here?

1 Answers

If K can be anything it could very well be some very corner case like never, void, unknown, any. The TS type system is so large that I wouldn't dare doing the kind of assumption that "K always extends itself".

I still don't get the use case: if the compiler would be explicitly told to expect the expression K extends K to always evaluate to true, the whole expression would be useless, just short circuiting to string, isn't it?

Is there a use case or is it just for the sake of it?

IMHO the use of extends expressions should be normally reserved to return values and parameters: when you have to assign a value to a constant or variable, your right side should evaluate to some specific value, with a specific type.

Finally, if you just need the expression to compile, because later on you will overwrite the value, just add as any and call it a day.

Related