如何在 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.
您需要先推断
brand
的类型:
type Extract_I<T> = T extends { brand: infer X } ? T extends infer V & { brand: X } ? V : never : never;