How do I define a type for
string|string[]|string[][]|string[][][] // ad infinitum
in typescript?
edit: the solution would be:
type Rec = string | string[] | Rec[]
but that is not allowed.
Here is my usecase:
interface RecursiveArray<T> {
[index: number]: (RecursiveArray<T> | T);
}
type Recursive<T> = T|RecursiveArray<T>
function stringValue (value: Recursive<string|boolean>): Recursive<string> {
if (typeof value === 'boolean') {
return value ? 'true' : 'false';
}
if (Array.isArray (value)) {
return (value).map (stringValue);
}
return stringValue(value);
}
Unlike the answer by Rodris you won't need to add any of the built in Array properties like map, length, etc.
type RecursiveArray = Array<RecursiveArray | string>;
let arr: RecursiveArray = [];
arr[1] = [];
arr[1][2] = [];
arr[1][2][2] = "item 122";
// In the other answer this throws a type error
arr[1][2][3] = ['1', '2', '3'];
arr[1][2][3].forEach(item => console.log(item));
You can create a recursive interface.
interface RecursiveArray {
[index: number]: (RecursiveArray | string);
length: number;
}
let arr: RecursiveArray = [];
arr[1] = [];
arr[1][2] = [];
arr[1][2][2] = "item 122";
arr[1][2][3] = "item 123";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With