【问题标题】:Get/extract the type of a type that is one of the types in a union type - typescript获取/提取作为联合类型中的类型之一的类型的类型 - 打字稿
【发布时间】:2021-12-30 17:44:13
【问题描述】:

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

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

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

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

【问题讨论】:

  • type A 总是有a 属性?或者应该是什么提取逻辑?如果是,您可以使用type A = Extract<UnionedType, { a: any }>
  • 我不明白这个问题。您能否提供更多示例和测试用例?
  • @AlekseyL。是的,就是这样。我用这个重要的细节更新了这个问题。我希望它现在更清楚。谢谢。

标签: typescript typescript-types


【解决方案1】:

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

答案:使用提取实用程序提取每个成员,以便您可以按名称引用它们。只需传入“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;
} */

【讨论】:

    猜你喜欢
    • 2020-05-09
    • 2019-03-27
    • 2017-05-18
    • 2022-09-29
    • 2021-12-14
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多