我有这些界面
interface CommonAnimalProps {
common: {
size: number,
weight: number,
origin: string,
}
}
interface DogProps extends CommonAnimalProps {
name: string
}
interface CatProps extends CommonAnimalProps {
furious: boolean
}
interface BirdProps extends CommonAnimalProps {
canFly: boolean
}
export enum AnimalType {
dog = "dog",
cat = "cat",
bird = "bird",
}
export interface AnimalTypeToAnimalPropsMap {
[AnimalType.dog]: (DogProps)[],
[AnimalType.cat]: (CatProps)[],
[AnimalType.bird]: (BirdProps)[]
}
export type AllAnimalValues<T> = T[keyof T]
export type AllAnimalTypesArray = AllAnimalValues<AnimalTypeToAnimalPropsMap>
export type AllAnimalTypes = AllAnimalValues<AnimalTypeToAnimalPropsMap>[0]
export type AllAnimalTypesArrayDiscriminating = AllAnimalTypes[]
这AllAnimalTypesArrayDiscriminating
将导致数组看起来像这样
const foo: AllAnimalTypesArrayDiscriminating = [
{
name: "Bello",
common: {
size: 10,
weight: 25,
origin: "Knowhwere"
},
},
{
furious: true,
common: {
size: 3,
weight: 5,
origin: "Anywhere"
},
},
{
canFly: false,
common: {
size: 39,
weight: 50,
origin: "Somewhere"
},
},
]
是否可以使用AllAnimalTypesArrayDiscriminating
并从中创建一个新的类型/接口(AllAnimalTypesArrayDiscriminatingModified
),其中结果数组中的每个元素bar
都有另一个 prop(color: string
)添加,CommonAnimalProps
以便结果如下所示
const bar: AllAnimalTypesArrayDiscriminatingModified = [
{
name: "Bello",
common: {
size: 10,
weight: 25,
origin: "Knowhwere",
color: 'red',
},
},
{
furious: true,
common: {
size: 3,
weight: 5,
origin: "Anywhere",
color: 'brown',
}
}, {
canFly: false,
common: {
size: 39,
weight: 50,
origin: "Somewhere",
color: 'white',
},
}
];
请注意,我无法修改原始内容CommonAnimalProps
以将其添加color
为可选参数。我也无法编辑DogProps, CatProps, BirdProps
。我正在寻找一种使用AllAnimalTypesArrayDiscriminating
(或任何其他我未排除的类型)来添加此属性的方法。有办法做到这一点吗?