1

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

what about this type Data = ReadonlyArray<number | Data>; ? WDYT?
what is the difference between readonly and ReadonlyArray here? they should be equivalent no?
@Radex readonly number[] is the same as ReadonlyArray<number> - readonly as a keyword is just more general, you can use ReadonlyArray<number | Data> just fine.
1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.