首页 > 其他分享 >[Typescript] Using Generic Context to Avoid Distributive Conditional Types

[Typescript] Using Generic Context to Avoid Distributive Conditional Types

时间:2022-12-12 16:01:03浏览次数:42  
标签:Typescript apple Generic Avoid never Fruit type banana AppleOrBanana

Let's say we have:

type Fruit = "apple" | "banana" | "orange";

 

We only want AppleOrBanana

If we do as such:

type Fruit = "apple" | "banana" | "orange";

type AppleOrBanana = Fruit extends "apple" | "banana"
  ? "apple" | "banana"
  : never;

type tests = [Expect<Equal<AppleOrBanana, "apple" | "banana">>]; // Doesn't work

It doesn't work, it will be never

 

Way to solve the problem, is using generic type T

type AppleOrBanana = Fruit extends infer T
  ? T extends "apple" | "banana"
    ? T
    : never
  : never;

The reason this is happening is when you use a generic like this, when you pull it out into T, then what happens is the members of the union distribute across it. T comes to represent each individual member of the union type.

If you don't do this, then this is no longer in a generic context. This is just itself Fruit. It compares the entire thing against the entire thing. It says, "Does this contain apple or banana?" It does contain apple or banana, but it also contains orange. What we end up with is never.

 

Solution 2:

type Fruit = "apple" | "banana" | "orange";

type GetAppleOrBanana<T> = T extends "apple" | "banana" ? T : never;

type AppleOrBanana = GetAppleOrBanana<Fruit>;

type tests = [Expect<Equal<AppleOrBanana, "apple" | "banana">>];

This T now is basically acting as the iterable. You iterate over. We check against apple, check against banana. If we do, then we return T

 

标签:Typescript,apple,Generic,Avoid,never,Fruit,type,banana,AppleOrBanana
From: https://www.cnblogs.com/Answer1215/p/16976290.html

相关文章