Skip to content

10. If #15

@astak16

Description

@astak16

题目

题目链接:If

实现 If,接收三个参数,第一个参数是条件,只能够是 boolean 类型,后面两个参数为任意类型,如果第一个参数为 true 则返回第二个参数,如果第一个参数为 false ,则返回第三个参数。

import type { Equal, Expect } from "@type-challenges/utils";

type cases = [
  Expect<Equal<If<true, "a", "b">, "a">>,
  Expect<Equal<If<false, "a", 2>, 2>>
];

// @ts-expect-error
type error = If<null, "a", "b">;

答案

方法一

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

知识点

这题有个 ts-expect-error ,所以第一个参数需要约束,只能传入 boolean 类型。

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions