Robert Brax
Robert Brax

Reputation: 7318

How to declare an array type that can contain either a string or other array?

Here is the variable declaration with type any:

let errorMessagesBag: any = []

erroMessagesBag must be able to hold a variable number of values that can be either a string, or a tuple of strings. Example

let errorMessagesBag = ["string1", ["tuplestring1", "otherString"], "string2"] // and so on

How to replace 'any' with proper type declaration in this case, so it accepts an array that contains strings OR a tuples of strings ?

Upvotes: 5

Views: 6844

Answers (4)

Burnee
Burnee

Reputation: 2623

Since typescript 3.7 you can create a general recoursive type:

type Tree<T> = T | Array<Tree<T>>

And then use it like this:

let errorMessagesBag: Tree<string> = ["string1", ["tuplestring1", "otherString"], "string2"];

Upvotes: 0

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

Just to extend correct answers - with a global custom type declaration:

type stringTypes = (string | string[]);
let errorMessagesBag: stringTypes[] = []

Upvotes: 5

Paleo
Paleo

Reputation: 23772

With union types:

let errorMessagesBag: (string | string[])[] = []

or

let errorMessagesBag: Array<string | string[]> = []

The two syntaxes are equivalent.

Upvotes: 4

Bruno Grieder
Bruno Grieder

Reputation: 29884

How about:

 const a: Array<string|string[]> = ["string1", ["tuplestring1", "otherString"], "string2"]

Upvotes: 0

Related Questions