The easiest way to do this is to have each interface have a common property that has a unique value for each type in the union. This is a discriminated union.
That might look something like:
interface TestA {
type: 'A'
Food: string
}
interface TestB {
type: 'B'
}
With that setup, you can test for item.type === 'A'
and then typescript knows that you have object of type TestA
.
That might look like this:
for (const item of selectedQueueItems) {
if (item.type === 'A') {
// item is known to be a TestA in this scope, since only TestA has: .type === 'A'
console.log(item.Food) // Works
}
}
If there is no property like that, you can still check for the properties presence before you access it with a 'key' in object
check.
for (const item of selectedQueueItems) {
if ('Food' in item) {
// item is known to be a TestA in this scope, since only TestA has .Food
console.log(item.Food) // Works
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…