8

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)[]
1
  • 2
    Are there common properties of the types? If so, I would create a common parent class or interface and that would be the type of the array. Why would you do this? Commented Jul 20, 2016 at 11:03

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

look into User-Defined Type Guards typescriptlang.org/docs/handbook/advanced-types.html - you can write custom functions to check the type of something if it could be one of several things - and then the compiler can do some amazing things like look at common properties between types and infer what the object can or can't be since it must be one of the types in your list
@Simon_Weaver type guard has nothing to do with the question. The OP asked about how to define the type of an array not how to check the type.
Fair point. I just thought it was a logical next step that might be useful. Rereading I could have been clearer that’s what I meant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.