Issue
Say I have the type
type Atom = string | boolean | number
. I want to define a type of array like:
NestedArray = Atom | [a_0, a_1, ... , a_n]
where each a_i
is an Atom
, or a NestedArray
.
Can this be achieved in Typescript?
Solution
Type aliases can't reference themselves, so this naïve approach will fail:
type NestedArray = Atom | Array<NestedArray | Atom> //Type alias 'NestedArray' circularly references itself.
Interfaces can however reference themselves:
interface NestedArray extends Array<NestedArray | Atom> {
}
And we can define an extra union at the top level to handle the root case:
type Atom = string | boolean | number
interface NestedArray extends Array<NestedArray | Atom> {
}
type AtomOrArray = Atom | NestedArray;
//Usage
let foo: AtomOrArray = [
"",
1,
[1, 2, ""]
]
let bar: AtomOrArray = ""
Answered By - Titian Cernicova-Dragomir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.