Need an array with multiple types in your Angular app? If so, then you're in luck.
TypeScript allows you to create an array with different types.
Now you might be thinking to yourself: why would I want to do that?
Let me answer yourself. You might want to do that if you're into charting.
Sometimes, charting solutions will use arrays with multiple types. You can see what I mean in this component class.
But for the purposes of this guide, I'll just show you how to do it.
How to Do It
For starters, instantiate the array as follows:
dataset: Array<string | number> = ;
Pay attention to the multiple generics.
Whereas you'd frequently instantiate an Array object with something like Array<string> or Array<number>, the code above uses both of those types.
The two types are, appropriately enough, separated by a pipe. That's a universal "or" sign in languages like TypeScript.
So the Array definition here says: "this array can accept either strings or numbers."
And, sure enough, you can push either a string or a number into that array. For example:
Both of those lines of code will compile just fine.
And yes, you can use custom types as well:
dataset: Array<User | Preferences | Customer> = ;
Something like that would work as long as those classes are defined in your application.
Wrapping It Up
Don't box yourself in. If you need an array with multiple types, let TypeScript be your best friend.
Just define the Array using all the generics you need to include. Then, populate it accordingly.
And make sure you have fun!
Photo by from