I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.
A little challange, let's write an util If which accepts condition C, a truthy return type T, and a falsy return type F. C is expected to be either true or false while T and F can be any type.
type A = If<true, 'a', 'b'> // expected to be 'a'
type B = If<false, 'a', 'b'> // expected to be 'b'
This one is a simple one, but a good practice
type If<C extends boolean, T, F> = C extends true ? T : F
We know C is of type boolean so we make sure it extends it, remember, C is expected to be either true or false, so according with our requirements, if C is true we return our type T otherwise we return our falsy type F.
Thank you!
you can find me here My Twitter
Top comments (0)