In my current code, I have the following working implementation:
type ParamType = { a: string, b: string } | { c: string }
if ('a' in params) {
doSomethingA(params)
} else {
doSomethingC(params)
}
The functions doSomethingA
and doSomethingC
each accept specific parameter types.
The issue arises when I modified a key within { a: string, b: string }
, TypeScript did not raise an error on 'a' in params
as expected. To address this, I made the following adjustments:
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 correctly infer the type of params
inside the if/else statement, resulting in:
Property 'd' is missing in type 'B' but required in type 'A'.
Is there a way to ensure that the key used in the if statement comes from type A while maintaining correct types within the if statement itself?