2

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);

1 Answer 1

1

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);

(code in playground)

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[]'
Sign up to request clarification or add additional context in comments.

3 Comments

sir compiler is giving an error "Duplicatie identifiers 'childs'" & "subsequent variable must have same type.variable childs must be of type number[][], but here has type '[number , number ,number]'" What should i do for this???
What is the code that results in those errors? (edit your question and add it there)
Thank u Sir , Code is now working . I havent initialized variables inside class constructor. I was initializing variables outside of constructor & was not using this keyword. Thank u

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.