Reputation: 137
How can i achieve following javascript code in typescript.
var childs = [];
childs[34] = [12,23,54,65];
childs[122] = [43,56,23,31];
childs[212343] = [345,643,24,745];
console.log(childs);
Upvotes: 2
Views: 10281
Reputation: 164139
Your code is already a valid typescript code as typescript is a superset of javascript.
However, typescript lets you have types, so in this case you can do this:
var childs: number[][] = [];
childs[34] = [12,23,54,65];
childs[122] = [43,56,23,31];
childs[212343] = [345,643,24,745];
console.log(childs);
Notice that the only thing I added was the type of childs
(number[][]
), which can also be written like:
var childs: Array<number[]> = [];
// or
var childs: Array<Array<number>> = [];
You'll get a compiler error if you try to add anything else to the array:
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[]'
Upvotes: 1