Open utterances-bot opened 1 year ago
Hey!
I found this solution too, but I don't have any compilation error (without adding extends boolean
to the type parameter C). It's normal?
type If<C, T, F> = C extends true ? T : F;
@AurelienWebnation maybe the type system became smart enough to figure it out? Try on the older versions of TypeScript if you are interested in getting an answer to this.
Such a solution will be more precise
type If<C extends boolean, T, F> = C extends true
? T
: C extends false
? F
: never;
@shadaxv I think your C extends false
condition is not necessary because this type parameter is constrained to boolean
. So if C extends true
, in the other case, C
can only extends
false.
This is correct for cases with a boolean type, but if you send another type and comment it out with // @ts-expect-error
, the returned type will be false
instead of never
, but maybe I'm just over-thinking it and it's not needed
Hi, using this type IF<T, K, L> = T extends true? K: L; I don't understand why with null the result is "true" type fromNull = IF<null, "true", "false">; //true
Hi, using this type IF<T, K, L> = T extends true? K: L; I don't understand why with null the result is "true" type fromNull = IF<null, "true", "false">; //true
You have something wrong, because the code you showed will return "false"
If
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/easy-if.html