Perplexityy
Perplexityy

Reputation: 569

Typescript - property '0' is missing in type

I don't understand what this error means. I am trying to declare an Array that contains arrays of two numbers. For instance,

[[1, 2], [4, 3], [5, 6]]

These are the type signatures I'm using.

const knightTour = (start: number[], size: number): void => {
    const [i, j] = start;
    let path: number[][] = [];
    const queue: Array<[number[]]> = [start];
}

However, I'm getting the aforementioned error when I try to initialise my queue variable. What am I doing wrong?

Upvotes: 0

Views: 181

Answers (2)

Odysseas
Odysseas

Reputation: 1060

To add to @axiac's answer:

The type:

[number[]]

is a Tuple type which matches arrays of size one, whose only element has type of number[].

So valid values for that type would be:

[[1, 2, 3]]
[[77, 33]]
[[]]

e.t.c. It is obvious that [number[]] is not a useful type. I would think that a tuple type makes sense if there are at least two elements in a tuple. For example this type:

[string, number, number[]]

could be used to store a string, a number and an array of numbers (if an application has a need for such a record).

['one', 1, [1]]
['six', 6, [1, 2, 3, 6]]
['ten', 10, [1, 2, 5, 10]]

In your case it's obvious that it's just a simple error. The intention seems to be that queue should be an array of arrays. So the type of queue can be just:

number[][]

and its definition and initialization:

const queue: number[][] = [start];

or just:

const queue = [start];

and let TypeScript infer the number[][] type.

Upvotes: 0

axiac
axiac

Reputation: 72226

The complete error message is:

(parameter) start: number[]
Property '0' is missing in type 'number[]' but required in type '[number[]]'.(2741)

and it reveals where the error is.

const queue: Array<[number[]]> = [start];

The type of queue is array of [number[]] (array of arrays of arrays of numbers) and you want tot initialize it with an array of arrays of numbers.

I suspect the type of queue is incorrect and it should be Array<number[]>.

Upvotes: 3

Related Questions