0

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?

westor
  • 1,426
  • 1
  • 18
  • 35

1 Answers1

4

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
}
Andrei Tătar
  • 7,872
  • 19
  • 37
  • ok, thank you. That does the trick. And with dot notation it's not possible for typescript to find out the right interface? – westor Feb 10 '22 at 10:47
  • You can try [StrictUnion](https://stackoverflow.com/questions/65805600/type-union-not-checking-for-excess-properties#answer-65805753) helper – captain-yossarian from Ukraine Feb 10 '22 at 10:51
  • @westor no, not as far as I know. – Andrei Tătar Feb 10 '22 at 11:00
  • @AndreiTătar I think, I know why: The property may be there, but it may also be null or undefined. Therefore it's not correct to use the dot if I want to find the correct contract. The only correct way is to check, if the property is there. Thank you again, that helped a lot. – westor Feb 10 '22 at 11:05