0

It never gives any array. Array accept only for one type. but tuples can allow multiple values.

var myTuple = [10,"Hello"];
console.log(myTuple[1]);

var myArray:number[] = [10,20,"Hello"];
console.log(myArray[2]);

[+] Update : my question, why doesn't it give any run time errors ?

6
  • whats the question? what IDE are you using? Commented Aug 24, 2021 at 12:03
  • Visual Studio Code , Question updated Commented Aug 24, 2021 at 12:04
  • It works fine in the typescript playground (i get the error): seems to be a misconfiguration. You'd have to provide your tsconfig.json typescriptlang.org/play?#code/… Commented Aug 24, 2021 at 12:05
  • It doesn't give any runtime errors, because typescript is compiletime only. TS is compiled to javascript, and in javascript there is no such thing as a myArray: number[] Commented Aug 24, 2021 at 12:07
  • @derpirscher Agreed. when i run tsc index.ts then it gives compile error. when i run tsc index.ts | node index.js then it works without having any issues :) Commented Aug 24, 2021 at 12:11

1 Answer 1

2

Typescript is a statically typed language that works compile-time and it eventually converts your code to pure Javascript. the code in your post will be converted to below js code:

var myTuple = [10, "Hello"];
console.log(myTuple[1]);
var myArray = [10, 20, "Hello"];   // notice how number[] is stripped away from your code
console.log(myArray[2]);

Since Javascript is a dynamically typed language, it has no issues with myArray. whereas in Typescript, you have specified before hand that myArray would be a number array type and TS being a statically typed language checks if the value assigned to myArray is indeed a number array or not, which in this case is not. so it raises the following error:

Type 'string' is not assignable to type 'number'.(2322)
Sign up to request clarification or add additional context in comments.

Comments

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.