patterntypescriptCritical
Exclude property from type
Viewed 0 times
excludetypepropertyfrom
Problem
I'd like to exclude a single property from the type. How can I do that?
For example I have
And I want to exclude property
For example I have
interface XYZ {
x: number;
y: number;
z: number;
}
And I want to exclude property
z to gettype XY = { x: number, y: number };
Solution
For versions of TypeScript at or above 3.5
In TypeScript 3.5, the
For versions of TypeScript below 3.5
In TypeScript 2.8, the
For versions of TypeScript below 2.8
You cannot use the
And an example of that type in use:
In TypeScript 3.5, the
Omit type was added to the standard library. See examples below for how to use it.For versions of TypeScript below 3.5
In TypeScript 2.8, the
Exclude type was added to the standard library, which allows an omission type to be written simply as:type Omit = Pick>For versions of TypeScript below 2.8
You cannot use the
Exclude type in versions below 2.8, but you can create a replacement for it in order to use the same sort of definition as above. However, this replacement will only work for string types, so it is not as powerful as Exclude.// Functionally the same as Exclude, but for strings only.
type Diff = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]
type Omit = Pick>And an example of that type in use:
interface Test {
a: string;
b: number;
c: boolean;
}
// Omit a single property:
type OmitA = Omit; // Equivalent to: {b: number, c: boolean}
// Or, to omit multiple properties:
type OmitAB = Omit; // Equivalent to: {c: boolean}Code Snippets
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>// 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}Context
Stack Overflow Q#48215950, score: 869
Revisions (0)
No revisions yet.