1
callbackFn(args: IGovedo | IKrava) {
   // How to check here type of args 
}

In the upper code as you can guess IGovedo and IKrava are interface types. If I use this approach what is the best way to check whether args is IGovedo, IKrava, null, or undefined?

The latest version 1.6 of typescript is used.

Edited: Not really duplicate of older question, but resolved - marked resolving answer.

netanalyzer
  • 634
  • 2
  • 6
  • 23

1 Answers1

3

What you need is user-defined type guard functions.

interface IGovedo {
    govedo: string;
}

interface IKrava {
    krava: string;
}

function isGovedo(object: any): object is IGovedo {
    return 'govedo' in object;
}

let foo: IGovedo | IKrava;

if (isGovedo(foo)) {
    // foo has type IGovedo;
} else {
    // foo has type IKrava.
}
vilicvane
  • 11,625
  • 3
  • 22
  • 27
  • Documentation link for reference: https://www.typescriptlang.org/docs/handbook/advanced-types.html – Ryan Q Sep 11 '16 at 08:57