给定
Person
类型
type Person = {
name: string,
age: number,
address: {
line1: string,
line2: string | null | number,
zip: string | number,
},
};
我想应用覆盖并修改此界面。
type PersonOverwrites = {
address: {
line2?: string,
zip: string,
},
};
我想从这两个界面创建以下内容:
type PersonModified = {
name: string,
age: number,
address: {
line1: string,
line2?: string,
zip: string,
},
}
这就是我要找的:
type PersonModified = Overwrite<Person, PersonOverwrites>
如何创建这种类型的泛型?
使现代化
应投诉:
type DeepMerge<T, U> = [T, U] extends [object, object] ?
{
[K in keyof (U & Pick<T, Exclude<keyof T, keyof U>>)]: (
K extends keyof U ? (
K extends keyof T ? DeepMerge<T[K], U[K]> : U[K]
) : (
K extends keyof T ? T[K] : never
)
)
} : U;
type Person = {
name: string,
age: number,
address: {
line1: string,
line2: string | null | number,
zip: string | number,
address?: {
line1: string,
line2: string | null | number,
zip: string | number,
address?: {
line1: string,
line2: string | null | number,
zip: string | number,
},
},
},
};
type PersonOverwrites = {
address: {
line2?: string,
zip: string,
address?: {
address: {
pizzaDelivery: boolean,
},
},
},
};
const person: Person = {
name: 'Thomas',
age: 12,
address: {
line1: 'hi',
line2: 'hi',
zip: 'hi',
address: {
line1: 'hi',
line2: 'hi',
zip: 'hi',
address: {
line1: 'hi',
line2: 'hi',
zip: 'hi',
// pizzaDelivery: true,
}
}
}
}