Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
utterances-bot opened this issue Jan 3, 2023 · 7 comments
Open

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

utterances-bot opened this issue Jan 3, 2023 · 7 comments

Comments

@utterances-bot
Copy link

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

Copy link
Contributor

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
Copy link
Owner

ghaiklor commented Jan 4, 2023

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

Copy link

shadaxv commented Jan 27, 2023

Such a solution will be more precise

type If<C extends boolean, T, F> = C extends true
  ? T
  : C extends false
  ? F
  : never;

Copy link
Contributor

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

Copy link

shadaxv commented Jan 27, 2023

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

Copy link

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
Copy link

shadaxv commented Apr 19, 2023

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants