-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
268 - If
This challenge gets you thinking about doing something that more closely resembles traditional programming, but in TypeScript's type system. Although it's not something that's very useful on its own, the skills required to implement it will be coming up quite a lot in the future.
🎥 Video Explanation
🔢 Code
import type { Equal, Expect } from './test-utils'
type A1 = If<true, 'a', 'b'>;
type B1 = 'a';
type C1 = Expect<Equal<A1, B1>>;
type A2 = If<false, 'a', 2>;
type B2 = 2;
type C2 = Expect<Equal<A2, B2>>;
// @ts-expect-error(2344)
type E1 = If<null, 'a', 'b'>
// ============= Your Code Here =============
type If<C extends boolean, T, F> =
C extends true
? T
: F
;
// ============== Alternatives ==============
// you can flip the expression if you want
type If<C extends boolean, T, F> =
C extends false
? F
: T
;
// nested condition not necessary
type If<C extends boolean, T, F> =
C extends true
? T
: C extends false
? F
: C
;
// equality check not necessary
type If<C extends boolean, T, F> =
Equal<C, true> extends true
? T
: F
;
// ================== NOPE ==================
// doesn't constrain `C`,
//so doesn't error for `null`
type Nope0<C, T, F> =
C extends false | null
? F
: T
;➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels