10

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?

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I added my comment in that issue, hopefully they will put that in their roadmap.
2

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

1 Comment

Yep, this is it!
0

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

2 Comments

I understand that but back to my question, how can I make sure when I am creating a class by implementing interface I am creating it with right modifier?
As I pointed, classes must redeclare the access attributes of their properties. There is no inheritance of property accesors from interfaces to classes. The only constraint is properties inferred from interfaces must be public, indeed.

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.