代码之家  ›  专栏  ›  技术社区  ›  Øystein Amundsen

将数组中的属性提取到联合类型中

  •  0
  • Øystein Amundsen  · 技术社区  · 3 年前

    我有一组对象:

    export const myArr = [
      { id: 'type 1', ... },
      { id: 'type 2', ... },
      { id: 'type 3', ... },
      ...
    ] as const;
    

    我想提取 id 属性转换为联合类型。 期望的结果是:

    export type MyTypes = 'type 1' | 'type 2' | 'type 3' | ...;
    

    我尝试过:

    export type MyTypes = Extract<(typeof myArr)[number], 'id'>;
    

    但编译器坚持将其作为 type MyTypes = never 。我做错了什么?

    1 回复  |  直到 3 年前
        1
  •  1
  •   rsp    3 年前

    ( jonrsharpe 在我完成回答之前,我是第一个发表评论的,但让我仍然发表评论来更详细地解释它)

    首先 Extract 效用类型是指做一些不同的事情——当你有例如类型时 A 和 B :

    type A = 'a' | 'b' | 'c';
    type B = 'b' | 'c' | 'd';
    

    则返回的类型 Extract<A, B> 提取联合类型的所有成员 A. 可以分配给类型 B 。

    另一个可能更有用的例子-对于type:

    type C = 'a' | 'b' | 1 | 10;

    类型 Extract<C, string> 是 'a' | 'b'

    有关更多详细信息,请参阅文档:

    例如,请参阅:

    enter image description here

    现在,要获得您想要的内容,您需要使用:

    type Id = (typeof myArr)[number]['id'];
    ``
    
    Or, using the `Pick` suggested in the comment you'd have to use:
    
    ```ts
    type Id = Pick<(typeof myArr)[number], 'id'>['id'];
    

    请注意,它比问题注释中的示例更复杂,因为 Pick<(typeof myArr)[number], 'id'> 会给您键入:

    type Id = {
        readonly id: "type 1" | "type 2" | "type 3";
    }
    

    是带键的对象类型 id 他就是那种 "type 1" | "type 2" | "type 3" ,而不仅仅是类型 “类型1”|“类型2”|“型号3” 你需要的。

    查看它在VSCode中的外观:

    enter image description here

    enter image description here

    推荐文章