colinfang colinfang - 1 year ago 70
TypeScript Question

Why doesn't interface protect me in this case?

interface IA {
readonly a: string;
f(x: string): void;

class X implements IA {
f(x) {
this.a = 1;

let x = new X().a;

Surprisingly, this code compiles.

  • It infers the type of
    , why is that?

  • readonly
    doesn't seem to protect me from modifying a. Am I using it wrong?


Answer Source

Pretty much down to any non-typed variable implicitly being any. You can disable that in the compiler options:

  "noImplicitAny": true

at which point you will have to define a type that can be assigned to the base-interface type.

enter image description here

as for the read-only. its working as intended:

enter image description here

you have to understand there are some differences between typescript and other OO languages like C#. Namely that the assignment of one typed variable to another is all about whether the right-side type intersects with the left-side type. i.e.

let x: X = { a: "hello", f: (x) => { } };

is perfectly valid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download