Skip to main content

If

introduction#

Implement a utils 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.

For example:

ts
type A = If<true, 'a', 'b'>; // expected to be 'a'
type B = If<false, 'a', 'b'>; // expected to be 'b'
ts
type A = If<true, 'a', 'b'>; // expected to be 'a'
type B = If<false, 'a', 'b'>; // expected to be 'b'
View on GitHub

start point#

ts
/* _____________ Your Code Here _____________ */
type If<C, T, F> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<If<true, 'a', 'b'>, 'a'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<If<false, 'a', 2>, 2>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
ts
/* _____________ Your Code Here _____________ */
type If<C, T, F> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<If<true, 'a', 'b'>, 'a'>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<If<false, 'a', 2>, 2>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
take the challenge

my solution#

Spoiler warning // Click to reveal answer
ts
type If<C, T, F> = C extends true ? T : F;
Try
ts
type If<C, T, F> = C extends true ? T : F;
Try
view more solutions