Let's take a look at this code
interface ImmutableValue<T> {
readonly value: T;
}
let i: ImmutableValue<string> = { value: "hi" };
i.value = "Excellent, I can't change it"; // compile-time error
The above is pretty straight forward, we have an interface ImmutableValue and since i is implementing that interface, i.value will be getting compilation error
Now consider the below code
interface Greetable {
readonly name: string;
}
class Person implements Greetable {
name: string;
constructor(n: string) {
this.name = n;
}
}
let user1 = new Person('isaac');
user1.name = 'jon'
console.log(user1)
For the code above, clearly Person is implementing Greetable which has a name of readonly and user1.name = 'jon' is a value reassignment and we should get an error. But TS is compiling perfectly fine, any idea why is that?
extendsan interface..extends, I mean in the sense of adding behaviour. Anything that expects a Greetable, something that has a readable name property, can still use Person. They don't be be able to write through that interface, the fact that another consumer accessing the same value through Person could is irrelevant.