I've been having difficulty creating a type that fits this specific data model:
Each node can be:
- native type
- string, number, boolean, null, undefined
- a list containing all the *same type* of nodes
- a dictionary of any type of nodes
While it's easy to come up with a type like this:
type Native = string | number | boolean | null | undefined;
type List = Array<Native | List | Dictionary>;
type Dictionary = { [key: string]: Native | List | Dictionary };
type Node = Native | List | Dictionary;
This approach fails to ensure that all elements in an array are of the same type. Here are some examples I need to address:
const value: Node = ["foo", "bar"] // Valid
const value: Node = ["foo", 1] // Invalid, elements are Native types but not all the same type
const value: Node = [] // Valid, empty arrays should also be allowed
const value: Node = 4; // Valid, Nodes can also be native values
const value: Node = {
a: 1,
b: "foo",
c: [ [1, 2, 3], ["a", "b", "c"] ],
d: {
e: {},
},
}; // Valid
If
c: [ [1, 2, 3], ["a", "b", 4] ],
is used instead in the last case above, then the entire declaration should be considered invalid.
How can I achieve this? Ideally, I would like to have the flexibility to change which native types are permitted by using a Native
type union, as shown in the example.