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

例如,我有

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

我要排除性质z

type XY = { x: number, y: number };

当前回答

在typescript 2.8中,可以使用新的内置Exclude类型。2.8版本说明实际上在“预定义条件类型”一节中提到了这一点:

注意:Exclude类型是Diff类型的正确实现 建议在这里。[…我们没有包括省略类型,因为 它可以简单地写成Pick<T, Exclude<keyof T, K>>。

将此应用到您的示例中,类型XY可以定义为:

type XY = Pick<XYZ, Exclude<keyof XYZ, "z">>

其他回答

我喜欢这样:

interface XYZ {
  x: number;
  y: number;
  z: number;
}
const a:XYZ = {x:1, y:2, z:3};
const { x, y, ...last } = a;
const { z, ...firstTwo} = a;
console.log(firstTwo, last);

如果您更喜欢使用库,请使用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)

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

在Typescript 3.5+:

interface TypographyProps {
    variant: string
    fontSize: number
}

type TypographyPropsMinusVariant = Omit<TypographyProps, "variant">

在typescript 2.8中,可以使用新的内置Exclude类型。2.8版本说明实际上在“预定义条件类型”一节中提到了这一点:

注意:Exclude类型是Diff类型的正确实现 建议在这里。[…我们没有包括省略类型,因为 它可以简单地写成Pick<T, Exclude<keyof T, K>>。

将此应用到您的示例中,类型XY可以定义为:

type XY = Pick<XYZ, Exclude<keyof XYZ, "z">>

我已经找到了解决方案,声明一些变量和使用扩散运算符推断类型:

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

declare var { z, ...xy }: XYZ;

type XY = typeof xy; // { x: number; y: number; }

它是有效的,但我很高兴看到一个更好的解决方案。