假设我有以下这些类型:
type BaseAnimal = {
species: string
owner: boolean
}
type Cat = BaseAnimal & {
species: 'cat'
hasTail: boolean
}
type Dog = BaseAnimal & {
species: 'dog'
likesWalks: boolean
}
type Animal = Cat | Dog
我希望创建一个名为AnimalParams
的类型,它与Animal
相同,只是 owner
属性是字符串。
我不能执行以下任何一项操作。
// This seems to keep the owner property from Animal instead of overwriting
// So it raises an error if I try to specify owner as a string
type AnimalParams = Animal & {
owner: string
}
// This strips away properties unique to Cat or Dog
// So it raises an error if I try to specify hasTail or likesWalks
type AnimalParams = Omit<Animal, 'owner'> & {
owner: string
}
现在,我能想到的唯一解决方法是按照以下步骤进行,但这似乎过于重复。有没有更加简洁、清晰的方法?
现在,我所能想到的唯一解决办法是按照上述方式操作,但这似乎过于重复。是否有更简便、更简明的方法?type CatParams = Omit<Cat, 'owner'> & {
owner: string
}
type DogParams = Omit<Dog, 'owner'> & {
owner: string
}
type AnimalParams = CatParams | DogParams
我在 Stack Overflow 上阅读了一些关于实用类型(如 在 TypeScript 的 d.ts 文件中覆盖接口属性类型,这是针对接口的),但是没有找到我需要的内容。感谢任何提前回答!