Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

I have a an array with elements representing a HTML form of types TextInput, DateInput, Checkbox and so on.

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

Something like this

(TextInput | DateInput | Checkbox)[]
like image 420
Sergei Basharov Avatar asked Jul 20 '16 11:07

Sergei Basharov


People also ask

Can TypeScript array have different types?

An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below. let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana']; // or let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];

How do you declare an array of objects in TypeScript interface?

One of which is Array of Objects, in TypeScript, the user can define an array of objects by placing brackets after the interface. It can be named interface or an inline interface.

How do you define object of objects type in TypeScript?

In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.

Should I use [] or array in TypeScript?

There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.


1 Answers

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 of defining arrays are equeivalent:

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

But sometimes the 2nd way fits better, like in your case.

like image 65
Nitzan Tomer Avatar answered Oct 01 '22 05:10

Nitzan Tomer