I’m trying to create an array of objects that can be passed into a react component. I’d like to require each potential object (within the array argument) passed in to match one of the potential types provided. So far, the union is allowing any fields provided in any of the various interfaces to be valid in other interfaces, when in reality I’d prefer it be more restrictive. I’ve been going through the documentation scanning over unions and control flow. I’m not sure if this can be done, but it seems like … perhaps it should be possible to accomplish in a dynamic way without having to be explicit?
interface IAnimal {
eat: () => void,
name: string
}
interface IDog extends IAnimal {
bark: () => void,
}
interface ICat extends IAnimal {
meow: () => void,
}
type ValidAnimals = IDog | ICat
// it needs to be either only a dog, or only a cat.
<MyComponent pets=[
{
name: "Sparky",
eat: () => {},
bark: () => {}
},
{
name: "Whiskers",
eat: () => {},
meow: () => {}
},
{
name: "Kitty",
eat: () => {},
bark: () => {} // this should be not allowed, does not exist on cats (casting doesn't resolve this)
meow: () => {}
},
]
/>
Is there a means to have typescript identify that the provided cat in this case does not exactly match any of the possible types (ICat / IDog) ?
2
Answers
Assigning a union type to your pets will infer that it is a dog or cat.
const pets: IDog | ICat
Yet, the line that will fail will be the second property on the "Kitty" object.
sure-