Typescript Connection Types: Working with Interfaces

What is the right way to handle the situation when you have two interfaces that are similar enough for you to run them through the same logic:

interface DescriptionItem { Description: string; Code: string; } interface NamedItem { Name: string; Code: string; } function MyLogic(i: DescriptionItem | NamedItem) { var desc = (<DescriptionItem>i).Description || (<NamedItem>i).Name; return i.Code + ' - ' + desc; } 

It works; however, my question is to improve the line var desc = ... Do I have the best option above? Or is there a better way to handle this situation in Typescript?

+7
typescript
source share
1 answer

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; } 
+5
source share

All Articles