I have to check an object. That may have different signatures. It should accept type and svc or id. Therefore I have two interfaces:
interface A {
type: string;
svc: string;
}
interface B {
id: string;
}
I saw an example, where they used a type and both interface combined with "or":
export type AB = A | B;
func(config: AB) {
if (config.type ) {
...
}
}
But this delivers an TS error in IDE:
TS2339: Property 'type' does not exist on type 'AB'. Property 'type' does not exist on type 'B'.
How is the correct way to implement this?
CodePudding user response:
You can change the check to
if ('type' in config) {
//because config contains a type property
//typescript knows config must be of type A in here
}