Hyyan Abo Fakher
Hyyan Abo Fakher

Reputation: 3527

Why typescript ReadonlyArrays are mutlabe when they are compiled to javascript

I am trying to learn Typescript from the official documentation. And in the Interfaces section I've read the following:

TypeScript comes with a ReadonlyArray type that is the same as Array with all mutating methods removed, so you can make sure you don’t change your arrays after creation:

I have played with the following sample code to test the case:

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!

and I found that the previous code is compiled to javascript like this

var a = [1, 2, 3, 4];
var ro = a;
ro[0] = 12; // works
ro.push(5); // works
ro.length = 100; // works
a = ro; // works

You can see that ro is mutable now in javascript, and other javascript code can change it, why typescript did not create a subclass of Array object where the mutable methods are removed for ro?! what I am missing here ?!

Upvotes: 4

Views: 302

Answers (2)

Pablo Lozano
Pablo Lozano

Reputation: 10342

That's because interfaces and types, like the access modifiers (private and public) are just Typescript concepts that don't survive the compilation process: While coding, the compiler/IDE will warn you when you are doing something wrong, but once your code becomes pure Javascript, nothing prevents you to assign a string to a number declared variable or to access a private member.

Just an example from the online demo:

enter image description here

You can see that there are two errors in the Typescript code (left):

  • that attribute is private
  • that attribute is not a number

But that code would be valid code once transpiled (actually, if you click on Run, it does).

Types and interfaces are useful just to help to detect potential errors, but they don't exist in runtime

Upvotes: 1

Fenton
Fenton

Reputation: 251082

TypeScript, on the whole, doesn't try to be invasive at runtime. There were discussions early on about things such as:

  • Enforcing types at runtime
  • Making private variables actually private at runtime

... and probably more subtle but similar questions.

The result was that TypeScript doesn't want to take over from JavaScript, so it works at design and compile time and outputs idiomatic JavaScript at the end.

This means there are many cases where TypeScript rules can be violated in other code such as access modifiers and read only arrays - but that isn't the goal of the project.

Upvotes: 5

Related Questions