这是indexloc提供的服务,不要输入任何密码
Skip to content

268 - If (🎥 Video Explanation and Solution) #21537

@dimitropoulos

Description

@dimitropoulos

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

Release Date: 2023-01-09 19:00 UTC

If

🔢 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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions