[英]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.
我正在尝试声明一个包含两个数字的 arrays 的数组。 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?
我究竟做错了什么?
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. queue
的类型是[number[]]
数组(arrays 数字数组的 arrays 数组),您想用数字数组 arrays 对其进行初始化。
I suspect the type of queue
is incorrect and it should be Array<number[]>
.我怀疑
queue
的类型不正确,应该是Array<number[]>
。
To add to @axiac's answer:要添加到@axiac 的答案:
The type:类型:
[number[]]
is a Tuple type which matches arrays of size one, whose only element has type of number[]
.是一个匹配大小为 1 的 arrays 的元组类型,其唯一元素的类型为
number[]
。
So valid values for that type would be:因此,该类型的有效值为:
[[1, 2, 3]]
[[77, 33]]
[[]]
etc. etc。 It is obvious that
[number[]]
is not a useful type.很明显
[number[]]
不是一个有用的类型。 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.意图似乎是
queue
应该是 arrays 的数组。 So the type of queue
can be just:所以
queue
的类型可以是:
number[][]
and its definition and initialization:及其定义和初始化:
const queue: number[][] = [start];
or just:要不就:
const queue = [start];
and let TypeScript infer the number[][]
type.并让 TypeScript 推断
number[][]
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.