This is an interesting question. The concept of the readonly property is subtly different from TypeScript to other languages.
In many languages, a property with a getter (but without a setter) could cause a compiler error if you tried to set the property, but TypeScript does not.
The property still remains in read mode only, because it does not matter if you try to set it; the set will fail.
Here is an example without any interfaces:
class Example { get name() { return 'Steve'; } } var y = new Example(); y.name = 'Example 2'; alert(y.name);
Compiler warnings when using x.name = 'Example 2'; does not exist.
If there was a warning about the compiler, I would subsequently expect it to be a way to specify readonly-ness properties inside the interface. As you expected, given the information above, you cannot set the readonly property on an interface.
interface Test { name: string; } class Example { get name() { return 'Steve'; } } var x: Test = new Example(); x.name = 'Example 1'; alert(x.name); var y = new Example(); x.name = 'Example 2'; alert(x.name);
This means that you can only use readonly-ness, having a method to get the value of the property (and, obviously, no method that allows you to set it).
interface Test { getName: () => string; } class Example { getName() { return 'Steve'; } } var x: Test = new Example();
Fenton
source share