Last updated: Mar 4, 2024
Reading timeยท3 min
The "Cannot set property which has only a getter" error occurs when trying to set a new value to a property, for which only a getter is defined.
To solve the error, define a setter for the specific property.
class Person { constructor(first, last) { this.first = first; this.last = last; } // ๐๏ธ getter get name() { return `${this.first} ${this.last}`; } } const p1 = new Person('John', 'Smith'); // โ Use getter console.log(p1.name); // โ๏ธ TypeError: Cannot set property name of #<Person> which has only a getter p1.name = 'John Doe';
We created a class in which we defined a name
getter.
The getter allows us to get the full name by accessing the name
property on an
instance of the class.
name
property on an instance of the class, the name()
getter method is run.We then attempt to update the value of the name
property of the instance.
However, we haven't defined a setter for the property.
To solve the error, define a setter for the property you are trying to update.
The set
syntax allows us to specify a function to be run when the specific
property is set.
class Person { constructor(first, last) { this.first = first; this.last = last; } get name() { return `${this.first} ${this.last}`; } // ๐๏ธ Define setter set name(name) { this.first = name.split(' ')[0]; this.last = name.split(' ')[1]; } } const p1 = new Person('John', 'Smith'); // โ Use setter p1.name = 'Bobby Hadz'; console.log(p1.name); // ๐๏ธ "Bobby Hadz"
We defined a setter for the name
property. This means that any time we try to
set the property on an instance, the setter method is run.
We updated the values of the first
and last
class properties in the method.
Here is another example of how the error occurs.
class Person { constructor(name) { // ๐๏ธ this causes the error this.name = name; } // ๐๏ธ getter get name() { return `Name: ${this.name}`; } } // โ๏ธ TypeError: Cannot set property name of #<Person> which has only a getter const p1 = new Person('bobby hadz');
The code in the constructor()
causes the error.
We defined a name()
getter so when we run the this.name = name
line in the
constructor, we are trying to use a setter
for the name
property.
You either have to rename your getter or you have to rename the property in the constructor.
Here is an example of renaming the getter
function.
class Person { constructor(name) { this.name = name; } // ๐๏ธ getter get get_name() { return `Name: ${this.name}`; } } const p1 = new Person('bobby hadz'); console.log(p1.get_name); // ๐๏ธ Name: bobby hadz
We renamed the getter to get_name
so now the name
instance variable doesn't
clash with the getter function.
When we access the get_name
property on an instance of the class, the
get_name
function is invoked.
You might also be interested in reading about private fields in JavaScript classes.
You can learn more about the related topics by checking out the following tutorials: