我有以下正在运行的代码:
type ParamType = { a: string, b: string } | { c: string }
if ('a' in params) {
doSomethingA(params)
} else {
doSomethingC(params)
}
doSomethingA
only accepts { a: string, b: string }
while doSomethingC
only accepts { c: string }
The issue I'm running into is I recently changed a key in { a: string, b: string }
and typescript didn't complain on the 'a' in params
as I would have liked. So I made the following update:
type A = { a: string, d: string }
type B = { c: string }
type ParamType = A | B
const testKey: keyof A = 'd'
if (testKey in params) {
doSomethingA(params)
} else {
doSomethingC(params)
}
however now typescript does not infer the type of params
correctly within the if/else and I get:
Property 'd' is missing in type 'B' but required in type 'A'.
Is there a way to ensure that the key I'm using in my if statement is one of the keys from A while also getting correct types within the if statement itself?