首页 > 其他分享 >[Typescript] Create a Union of Strings with All Possible Permutations of Two Unions

[Typescript] Create a Union of Strings with All Possible Permutations of Two Unions

时间:2022-12-11 21:57:06浏览次数:59  
标签:cheese Typescript Union Create rye Sandwich Filling BreadType type

Here we have a Sandwich type that's currently assigned to unknown

We also have a couple of union types, BreadType and Filling, that have several options as members:

type BreadType = "rye" | "brown" | "white";

type Filling = "cheese" | "ham" | "salami";

 

We can create a new union type with all possible permutations of two unions:

type Sandwich = `${BreadType} sandwich with ${Filling}`;

 

import { Equal, Expect } from "../helpers/type-utils";

type BreadType = "rye" | "brown" | "white";

type Filling = "cheese" | "ham" | "salami";

type Sandwich = `${BreadType} sandwich with ${Filling}`;

type tests = [
  Expect<
    Equal<
      Sandwich,
      | "rye sandwich with cheese"
      | "rye sandwich with ham"
      | "rye sandwich with salami"
      | "brown sandwich with cheese"
      | "brown sandwich with ham"
      | "brown sandwich with salami"
      | "white sandwich with cheese"
      | "white sandwich with ham"
      | "white sandwich with salami"
    >
  >
];

 

标签:cheese,Typescript,Union,Create,rye,Sandwich,Filling,BreadType,type
From: https://www.cnblogs.com/Answer1215/p/16974589.html

相关文章