如何在打字稿中创建数组并为任何索引赋值



如何在打字稿中实现以下JavaScript代码。

var childs = [];
childs[34] = [12,23,54,65];
childs[122] = [43,56,23,31];
childs[212343] = [345,643,24,745];
console.log(childs);

你的代码已经是一个有效的打字稿代码,因为打字稿是javascript的超集。

但是,打字稿允许您拥有类型,因此在这种情况下,您可以执行以下操作:

var childs: number[][] = [];
childs[34] = [12,23,54,65];
childs[122] = [43,56,23,31];
childs[212343] = [345,643,24,745];
console.log(childs);

(操场上的代码(

请注意,我添加的唯一内容是childs的类型(number[][](,也可以这样写:

var childs: Array<number[]> = [];
// or
var childs: Array<Array<number>> = [];

如果尝试向数组添加任何其他内容,则会收到编译器错误:

childs.push(4); // error: Argument of type '4' is not assignable to parameter of type 'number[]'
childs.push([2, "4"]); // error: Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'

最新更新