Radex
Radex

Reputation: 8587

Typescript recursive types for array of array

I want describe some data as where a value in the array could be another array of numbers, this is done indefinitely so the types should be recursive.

With the following code I receive an error

Type 'number' is not assignable to type 'Data'

type Data = ReadonlyArray<number> | Data[];
const data: Data = [1, 2, 3, [4, 5, [6, 7]]];

How to fix it using the latest TypeScript?

Upvotes: 1

Views: 198

Answers (2)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

type E = number

type ListOfE = E[]

type NestedListOfE = (E | NestedListOfE)[]

const a: E = 10
const b: ListOfE = [ 1, 2, 3 ]
const c: NestedListOfE = [ 1, 2, [ 3, [ 4, 5 ] ] ]

Note usage of recursive types is only available since TS 3.7.

Upvotes: 1

Chase
Chase

Reputation: 5615

Typescript treats an array type of unions and unions of array very differently. Something like [1, 2, 3, [4, 5]] is actually of type (number | number[])[] - which is not assignable to number[] | number[][].

This means that you need an array of unions, where the union can circularly reference itself.

type Data = readonly (number | Data)[];

The above will declare a readonly array of the recursive atom, number. Now you'll be able to assign [1, 2, 3, [4, 5, [6, 7]]]

Try it out on playground

Upvotes: 1

Related Questions