跳到主要内容

If

介绍

实现一个 IF 类型,它接收一个条件类型 C ,一个判断为真时的返回类型 T ,以及一个判断为假时的返回类型 FC 只能是 true 或者 falseTF 可以是任意类型。

例子:

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

起点

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'.
];
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'.
];
take the challenge

解决方案

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