TypeScript is the interface signature for a property without a setter.

We have a typical getter in one of our classes, say

class Employee implements IEmployee { private _fullName: string; get fullName(): string { return this._fullName; } } 

and interface for working with it

 interface IEmployee{ fullName: string; } 

When working with an instance through this interface, the compiler will not warn us about the absence of a setter if we try to assign fullName, and the JS runtime simply swallows any task and does not give an error. Is there a way to mark an interface member as having only getter or only setter?

I saw this post , but it's quite old, I want to know if something improves.

+8
properties interface setter getter typescript
source share
2 answers

Properties in typewriting can now have a read-only modifier that allows you to achieve the desired result.

 interface IEmployee{ readonly fullName: string; } 
0
source share

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(); //x.getName('Obviously not'); //x.getName() = 'Obviously not'; alert(x.getName()); var y = new Example(); //y.getName('Obviously not'); //y.getName() = 'Obviously not'; alert(y.getName()); 
+1
source share

All Articles