patterntypescriptCritical
Defining array with multiple types in TypeScript
Viewed 0 times
arraytypescriptwithdefiningmultipletypes
Problem
I have an array of the form:
How would I define this in TypeScript?
[ 1, "message" ].How would I define this in TypeScript?
Solution
Defining array with multiple types in TypeScript
Use a union type
I have an array of the form: [ 1, "message" ].
If you are sure that there are always only two elements
And you can even provide meaningful names for the tuple members e.g.
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" ];And you can even provide meaningful names for the tuple members e.g.
id and text:const foo: [id: number, text: string] = [ 1, "message" ];Code Snippets
const foo: (string|number)[] = [ 1, "message" ];const foo: [number, string] = [ 1, "message" ];const foo: [id: number, text: string] = [ 1, "message" ];Context
Stack Overflow Q#29382389, score: 855
Revisions (0)
No revisions yet.