I am interested in modifying the data types of specific fields to a customized type.
For instance, I would like to transform the b field of TSomeType into a custom type, resulting in TSomeTypeConverted type.
// initial type
type TSomeType = {
a: boolean;
b: string;
}
// desired outcome
type TSomeTypeConverted = {
a: boolean;
b: TCustomType;
}
A similar transformation can be achieved using the TConvertToCustomType method below.
type TConvertToCustomType<T, K extends keyof T> = Omit<T, K> & {[P in K]: TCustomType};
type TSomeTypeConverted = TConvertToCustomType<TSomeType, 'b'>
/* type TSomeTypeConverted = {
a: boolean;
b: TCustomType;
} */
However, this process results in all optional values becoming required.
// prior to modification
type TSomeType = {
a: boolean;
b: string;
c?: string; // optional
}
type TSomeTypeConverted = TConvertToCustomType<TSomeType, 'b' | 'c'>
/* type TSomeTypeConverted = {
a: boolean;
b: TCustomType;
c: TCustomType; // no longer optional
} */
Is there a way to change only the data type while preserving the optional status?