我想从类型中排除一个属性。我该怎么做呢?
例如,我有
interface XYZ {
x: number;
y: number;
z: number;
}
我要排除性质z
type XY = { x: number, y: number };
我想从类型中排除一个属性。我该怎么做呢?
例如,我有
interface XYZ {
x: number;
y: number;
z: number;
}
我要排除性质z
type XY = { x: number, y: number };
当前回答
对于TypeScript 3.5或以上的版本
在TypeScript 3.5中,省略类型被添加到标准库中。关于如何使用它,请参见下面的示例。
对于TypeScript 3.5以下的版本
在TypeScript 2.8中,Exclude类型被添加到标准库中,这使得省略类型可以简单地写成:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
对于TypeScript 2.8以下的版本
在2.8以下的版本中不能使用Exclude类型,但是可以为它创建一个替换,以便使用与上面相同的定义类型。但是,这个替换只适用于字符串类型,所以它没有Exclude那么强大。
// 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}
其他回答
我已经找到了解决方案,声明一些变量和使用扩散运算符推断类型:
interface XYZ {
x: number;
y: number;
z: number;
}
declare var { z, ...xy }: XYZ;
type XY = typeof xy; // { x: number; y: number; }
它是有效的,但我很高兴看到一个更好的解决方案。
如果您更喜欢使用库,请使用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或以上的版本
在TypeScript 3.5中,省略类型被添加到标准库中。关于如何使用它,请参见下面的示例。
对于TypeScript 3.5以下的版本
在TypeScript 2.8中,Exclude类型被添加到标准库中,这使得省略类型可以简单地写成:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
对于TypeScript 2.8以下的版本
在2.8以下的版本中不能使用Exclude类型,但是可以为它创建一个替换,以便使用与上面相同的定义类型。但是,这个替换只适用于字符串类型,所以它没有Exclude那么强大。
// 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}
在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">>