Get/extract 类型的类型,它是联合类型中的一种类型 - 打字稿

Get/extract the type of a type that is one of the types in a union type - typescript

给定一个存在于生成文件中的联合类型:

    export type UnionedType = {a: number; ...otherProps;} | {b: string; ...otherProps;};

如何提取每个内联类型的类型?也就是说,如果内联成员 {a: number; ...otherProps;} 总是有一个名为“a”的道具,而内联成员 {b: number; ...otherProps;} 一个名为“b”的道具。

每次生成“UnionedType”时,最好提取可能的类型:如 type A = {[outputOfSomeTypeMagic <P , UnionedType>]};,这样在魔术 type A = {a: number; ...otherProps;}.

之后

@Aleksey L. 准确地指出我只是在描述 TypeScript 全局的目的 Extract utility.

答:使用 Extract 实用程序提取每个成员,以便您可以按名称引用它们。只需传入“UnionedType”和一个与您要提取的成员匹配的接口:

//export type UnionTypeOfAB = { a: {}; id: number } | { b: {}; id: number };
import {UnionTypeOfAB} from './generated.ts';

interface A {
  a: {};
}

interface B {
  b: {};
}

type A_Type = Extract<UnionTypeOfAB, A>; 
// can use an inline interface instead of declaring one:
//type A_Type = Extract<UnionTypeOfAB, {a:{}}>;

/*A_type result:
 type A_Type = {
  a: {};
  id: number;
} */

type B_Type = Extract<UnionTypeOfAB, B>;
/*B_type result:
 type B_Type = {
  b: {};
  id: number;
} */