从品牌类型中提取类型

问题描述 投票:0回答:1

如何在 TypeScript 中提取品牌类型的类型?

它适用于非文字品牌:

type Branded = string & {
  brand: string;
};

type Extract_I<T> = T extends infer V & { brand: string } ? V : never;

type Result_I = Extract_I<Branded>; // => string

但不适用于字面品牌:

type LiteralBranded = string & {
  brand: 'brand';
};

type Result_II = Extract_I<LiteralBranded>; // =>  string & { brand: "brand" }

我怎样才能做到这一点?

这是我尝试过的其他方法:

type Extract_II<T> = T extends { brand: string } ? T & { brand: never } : never; // does not work.
typescript types branding
1个回答
0
投票

您需要先推断

brand
的类型:

游乐场

type Extract_I<T> = T extends { brand: infer X } ? T extends infer V & { brand: X } ? V : never : never;
© www.soinside.com 2019 - 2024. All rights reserved.