If I have a type with all required properties, how can I define another type with the same properties where some of it's properties are still required but the rest are optional?
For example I want a new type derived from SomeType where prop1 and prop2 are required but the rest are optional:
interface SomeType {
prop1;
prop2;
prop3;
...
propn;
}
interface NewType {
prop1;
prop2;
prop3?;
...
propn?;
}
Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!
In typescript, the optional parameter is defined as a parameter that can be made optional while passing the values when the function is called and the values that are passed when the function is called is printed with no errors but when the functions have declared the parameters that are ending with “?” are marked as ...
The declaration of the interface is a place to make some properties optional. You can achieve that with a question mark next to the properties names.
Inside the brackets, we can define the name of the property followed by the ? (question mark) and : (colon) symbol, and finally the type of property to make it an optional object property in TypeScript. To end the type declaration we can either use the ; symbol (semi-colon) or the , symbol (comma).
You can use combination of Partial
and Pick
to make all properties partial and then pick only some that are required:
interface SomeType {
prop1: string;
prop2: string;
prop3: string;
propn: string;
}
type OptionalExceptFor<T, TRequired extends keyof T> = Partial<T> & Pick<T, TRequired>
type NewType = OptionalExceptFor<SomeType, 'prop1' | 'prop2'>
let o : NewType = {
prop1: "",
prop2: ""
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With