TypeScript interfaces exist only at compile time, so not much can be checked for interface types at runtime. The code you provided in your question makes sense and is probably your best bet.
However, if you have the flexibility to change interfaces to classes , you can use the TypeScript type of protection for more elegant type checking:
class DescriptionItem { Description: string; Code: string; } class NamedItem { Name: string; Code: string; } function MyLogic(i: DescriptionItem | NamedItem) { let desc: string; if (i instanceof DescriptionItem) { desc = i.Description; } else { desc = i.Name; } return i.Code + ' - ' + desc; }
Nathan friend
source share