代码之家  ›  专栏  ›  技术社区  ›  ThomasReggi

从没有属性或属性列表的接口创建类型[重复]

  •  0
  • ThomasReggi  · 技术社区  · 6 年前

    我想从类型中排除一个属性。我该怎么做?

    例如我有

    interface XYZ {
      x: number;
      y: number;
      z: number;
    }
    

    我想排除财产 z 得到

    type XY = { x: number, y: number };
    
    0 回复  |  直到 5 年前
        1
  •  167
  •   CRice    5 年前

    对于3.5或以上版本的typescript

    在TypeScript3.5中, Omit 类型已添加到标准库。请参阅下面的示例以了解如何使用它。

    对于低于3.5的typescript版本

    在TypeScript2.8中, Exclude 类型已添加到标准库中,允许将省略类型简单地编写为:

    type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
    

    对于低于2.8版本的typescript

    你不能使用 排除 键入低于2.8的版本,但可以为其创建替换项,以便使用与上面相同的定义。但是,这种替换只适用于字符串类型,因此它不如 排除 .

    // Functionally the same as Exclude, but for strings only.
    type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
    type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>
    

    以及正在使用的这种类型的示例:

    interface Test {
        a: string;
        b: number;
        c: boolean;
    }
    
    // Omit a single property:
    type OmitA = Omit<Test, "a">; // Equivalent to: {b: number, c: boolean}
    
    // Or, to omit multiple properties:
    type OmitAB = Omit<Test, "a"|"b">; // Equivalent to: {c: boolean}
    
        2
  •  33
  •   Jason Hoetger    6 年前

    对于typescript 2.8,您可以使用新的内置 Exclude 类型。这个 2.8 release notes 实际上在“预定义条件类型”一节中提到了这一点:

    注意:exclude类型是diff类型的正确实现 在这里建议。[…]我们没有包含省略类型,因为 它被琐碎地写为 Pick<T, Exclude<keyof T, K>> .

    将此应用于示例时,类型xy可以定义为:

    type XY = Pick<XYZ, Exclude<keyof XYZ, "z">>
    
        3
  •  16
  •   Qwertiy    7 年前

    我找到了 solution 通过声明一些变量并使用Spread运算符推断类型:

    interface XYZ {
      x: number;
      y: number;
      z: number;
    }
    
    declare var { z, ...xy }: XYZ;
    
    type XY = typeof xy; // { x: number; y: number; }
    

    这是可行的,但我很高兴看到更好的解决方案。

        4
  •  2
  •   Krzysztof Kaczor    5 年前

    如果您喜欢使用库,请使用 ts-essentials .

    import { Omit } from "ts-essentials";
    
    type ComplexObject = {
      simple: number;
      nested: {
        a: string;
        array: [{ bar: number }];
      };
    };
    
    type SimplifiedComplexObject = Omit<ComplexObject, "nested">;
    
    // Result:
    // {
    //  simple: number
    // }
    
    // if you want to Omit multiple properties just use union type:
    type SimplifiedComplexObject = Omit<ComplexObject, "nested" | "simple">;
    
    // Result:
    // { } (empty type)
    

    附言:你会发现很多其他有用的东西;)

        5
  •  2
  •   GonchuB    5 年前

    打字本3.5

    从TypeScript3.5开始,省略助手将包括: TypeScript 3.5 RC - The Omit Helper Type

    您可以直接使用它,并且在更新时应该删除自己对省略帮助器的定义。