Make all properties within a Typescript interface optional
If I want to have an explicit AssetDraft
interface, I would use a combination of extends
and Partial
:
interface Asset {
id: string;
internal_id: string;
usage: number;
}
interface AssetDraft extends Partial<Asset> {}
This isn't possible in TypeScript < 2.1 without creating an additional interface with optional properties; however, this is possible by using mapped types in TypeScript 2.1+.
To do this, use the Partial<T>
type which TypeScript provides by default.
interface PostDraft {
asset: Partial<Asset>;
}
Now all the properties on asset
are optional, which will allow you to do the following:
const postDraft: PostDraft = {
asset: {
id: "some-id"
}
};
About Partial<T>
Partial<T>
is defined as a mapped type that makes every property in the provided type optional (using the ?
token).
type Partial<T> = {
[P in keyof T]?: T[P];
};
Read more about mapped types here and in the handbook.
Deep Partial
If you want a partial implementation that works recursively on objects then you can use the following type in TS 4.1+:
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};