How do I make a TypeScript property that could have multiple types?
I'm working on an app for a client and as with many apps was displaying a list of items. I needed to loop over this list and display items. Every UI framework has some way to do this.
This was an Angular app using TypeScript, so I making use of TypeScript's statically typed nature. My problem was that the objects in this list could be one of two types, let's call those Type1 or Type2. I was running into errors when transpiling the code. I had defined the type like this on the class:
myItems: Type1[];
This code created an array of Type1 arguments. IT wasn't until later that Type2 was added as a possible value in this list.
When updating the code to accommodate for Type2 I realized that sometimes I was receiving errors by accessing Type2 specific properties on a Type1 argument. What was the solution? I used something called Union types. I set up my value like this:
myItems: (Type1 | Type2)[];
This means that myItems can be a mixed array of Type1 and Type2 values.
That works great as long as all properties that you access in Type1 are also in Type2. If a property that you're accessing in one and not the other exists, then you'll get errors--these were the same errors I started with. I solved that issue by adding blank getters to the class definition:
get mySharedProperty(){ return null};
Far from perfect, but functional for my purposes.
Maybe I should have just created an interface and had both Type1 and Type2 extend it?
There are no comments for this entry.
[Add Comment] [Subscribe to Comments]