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)[]
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'];
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.
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.
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.
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.
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