ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
471 stars 56 forks source link

type-challenges-solutions/en/easy-if #315

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

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

AurelienWebnation commented 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;
ghaiklor commented 1 year ago

@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.

shadaxv commented 1 year ago

Such a solution will be more precise

type If<C extends boolean, T, F> = C extends true
  ? T
  : C extends false
  ? F
  : never;
AurelienWebnation commented 1 year ago

@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.

shadaxv commented 1 year ago

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

fabiangambetta commented 1 year ago

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

shadaxv commented 1 year ago

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"