I'm facing an issue with narrowing down a union type in typescript.
Let's say we have two interfaces and a union:
interface A {
flag: true
callback: (arg: string) => void
}
interface B {
flag?: false
callback: (arg: number) => void
}
type AB = A | B
This is narrowed down correctly:
const testA: AB = {
flag: true,
callback: arg => {
// typescript recognizes this as interface A and arg as a string
}
}
const testB: AB = {
flag: false,
callback: arg => {
// typescript identifies this as interface B and arg as a number
}
}
However, this scenario does not work:
const testC: AB = {
// flag is implied as undefined
callback: arg => {
// typescript cannot determine if this is A or B
// arg is implicitly any
}
}
What could I be missing?
Here is a link to typescript playground
Thank you in advance