Reputation: 7318
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
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
Reputation: 123901
Just to extend correct answers - with a global custom type
declaration:
type stringTypes = (string | string[]);
let errorMessagesBag: stringTypes[] = []
Upvotes: 5
Reputation: 23772
With union types:
let errorMessagesBag: (string | string[])[] = []
or
let errorMessagesBag: Array<string | string[]> = []
The two syntaxes are equivalent.
Upvotes: 4
Reputation: 29884
How about:
const a: Array<string|string[]> = ["string1", ["tuplestring1", "otherString"], "string2"]
Upvotes: 0