【发布时间】:2020-11-05 18:14:49
【问题描述】:
假设我有这些类型:
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
我阅读了一些关于实用程序类型的 SO 线程(例如用于接口的 Overriding interface property type defined in Typescript d.ts file),但找不到我需要的东西。感谢您提前提供任何答案!
【问题讨论】:
标签: typescript types .d.ts