I have an array of the form: [ 1, "message" ]
.
How would I define this in TypeScript?
Use a union type to define an array with multiple types in TypeScript, e.g. const arr: (string | number)[] = ['a', 1] . A union type is formed from two or more other types. The array in the example can only contain values of type string and number .
Summary. In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.
You can create an array with elements of different data types when declare the array as Object. Since System. Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.
TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.
Defining array with multiple types in TypeScript
Use a union type (string|number)[]
demo:
const foo: (string|number)[] = [ 1, "message" ];
I have an array of the form: [ 1, "message" ].
If you are sure that there are always only two elements [number, string]
then you can declare it as a tuple:
const foo: [number, string] = [ 1, "message" ];
IMPORTANT NOTE
This won't work with complex types with different properties, when you want to access a property available on only one of the types.
See this newer answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With