How to declare an array of objects of different types in TypeScript?

I have an array with elements representing the HTML form of types TextInput, DateInput, Checkbox, etc.

How to declare a variable type as an array of elements that can be any of these types?

Something like that

(TextInput | DateInput | Checkbox)[]
+4
source share
1 answer

You can do:

let myArray: Array<TextInput | DateInput | Checkbox> = [];

And you can also do:

type MyArrayTypes = TextInput | DateInput | Checkbox;
let myArray: MyArrayTypes[] = [];

These two ways to define arrays are equidistant:

let a: number[] = [];
// is just like:
let b: Array<number> = [];

But sometimes the second method works better, as in your case.

+6
source

Source: https://habr.com/ru/post/1648489/


All Articles