Saeid Ostad
Saeid Ostad

Reputation: 727

Typescript Class implements Interface does not respect readonly modifier

I want to create class base on interface but it looks link it does not respect readonly modifier.

code below works without compiler error:

interface I {
  readonly a: string
}

class C implements I{
  a= ""
}
const D = new C
D.a = "something"

in order to make property 'a' really readonly I should make it readonly in class definition too! so what's the use case on readonly modifier in interface definition?

in other word how can I make sure when I am creating a class by implementing interface I creating it with right modifier?

Upvotes: 10

Views: 1798

Answers (3)

Michael Tidwell
Michael Tidwell

Reputation: 381

You would need to define the type of "D" early, note I made "D" into lowercase "d"

interface I {
  readonly a: string
}

class C implements I{
  a= ""
}
let d: I // THIS IS NEEDED
d = new C
d.a = "something" // NOW THIS WON'T WORK

Upvotes: 2

Evert
Evert

Reputation: 99851

Even more concerning and surprising, is that the opposite is also true. An object with a readonly property can satisfy the type of an object where that property is not read-only.

I found this issue: https://github.com/microsoft/TypeScript/issues/18770

It's open, this could suggest that there is interest in fixing this somehow and somewhat acknowledged as a problem.

Upvotes: 2

VRoxa
VRoxa

Reputation: 1051

The main idea of readonly keyword in an interface is the constraint in case of declaring an object of the interface type.

interface ITest {
    readonly a: string;
}

const t: ITest = {
    a: 'readonly'
}

t.a = 'another value'; // -> Compiler error

When implementing an interface in a class, the class must redeclare the access attributes of the properties inferred

interface ITest {
    readonly a: string;
    b: string;
    c: string;
}

class ATest implements ITest {
    a: string = ``;
    constructor(public b: string, public c: string) { }
}

const t = new ATest('b', 'c');
t.a = 'another value'; // This is OK

Upvotes: 0

Related Questions