Working with auto generated types from a library poses a challenge for me. The types currently have all values as required, but I would like to mark some of them as optional. While I know this can be achieved using generics in typescript, I am unsure about the exact approach. To better illustrate, consider the following example:
Here is a sample type structure with nested types:
interface Person {
name: string;
hometown: string;
nickname: string;
data:{
address:string,
phone:number
}
}
I intend to apply an operation similar to the following to designate the name
property in the root type and the address
property in the nested type as optional:
type TransformedPerson = MakeOptional<Person,{name:string, data:{address:string}}>
or:
type TransformedPerson = MakeOptional<Person,"name"|"data.address">
The expected result should resemble the type created below:
/*
type TransformedPerson = {
name?: string;
hometown: string;
nickname: string;
data:{
address?:string,
phone:number
}
}
*/
An attempt was made to utilize the Partial in nested property with typescript method to make properties optional in the root object but it proved ineffective for nested types:
type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
type PartialExcept<T, K extends keyof T> = RecursivePartial<T> & Pick<T, K>;
type TransformedType = PartialExcept<Person, "name"> /// This works only for root type
type TransformedType = PartialExcept<Person, "name"|"data.address"> /// throws error