Consider the following types:
type BaseAnimal = {
species: string
owner: boolean
}
type Cat = BaseAnimal & {
species: 'cat'
hasTail: boolean
}
type Dog = BaseAnimal & {
species: 'dog'
likesWalks: boolean
}
type Animal = Cat | Dog
Now, let's say we need a type called AnimalParams
. This type should be similar to Animal
but with a different type for the owner
property, which should be a string.
There are limitations to achieving this directly as shown below:
// This approach retains the original owner property instead of replacing it
// Therefore, specifying owner as a string results in an error
type AnimalParams = Animal & {
owner: string
}
// This method removes unique properties from Cat or Dog types
// As a result, trying to specify hasTail or likesWalks leads to errors
type AnimalParams = Omit<Animal, 'owner'> & {
owner: string
}
One way to work around this limitation is by creating separate types for each animal as shown below. However, this solution appears repetitive. Is there a more concise and cleaner approach?
type CatParams = Omit<Cat, 'owner'> & {
owner: string
}
type DogParams = Omit<Dog, 'owner'> & {
owner: string
}
type AnimalParams = CatParams | DogParams
I've explored some Stack Overflow threads on utility types but couldn't find a suitable solution yet. Any suggestions are appreciated. Thank you!