Last active
March 16, 2024 21:09
-
-
Save e0ipso/8faddc9a362c31ddc9f9 to your computer and use it in GitHub Desktop.
Read only property ES6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Class that holds a read only property. | |
*/ | |
class PropertyBag { | |
/** | |
* Accessor. | |
* | |
* @return {string} | |
* The value. This annotation can be used for type hinting purposes. | |
*/ | |
static get readOnly() { | |
return 'This property can only be read.'; | |
} | |
/** | |
* Mutator. | |
* | |
* @param {*} value | |
* The passed in value. | |
* | |
* @throws {Error} | |
* Inconditionally. | |
* @return {void} | |
*/ | |
static set readOnly(value) { | |
throw new Error(`The readOnly property cannot be written. ${value} was passed.`); | |
} | |
} | |
console.log(PropertyBag.readOnly); // This property can only be read. | |
PropertyBag.readOnly = 'Ha!'; // Error: The readOnly property cannot be written. Ha! was passed. |
class Todo {
constructor(data) {
this.__getId__ = function () { return data.id };
}
get id() { return this.__getId__(); }
}
var todo = new Todo({id: 123456});
console.log(todo.id); // return 123456
todo.id = 654321;
console.log(todo.id); // return 123456
OR
class Todo {
constructor(data) {
this.__getId__ = function () { return data.id };
}
get id() { return this.__getId__(); }
set id(v) { throw new Error('Todo id property is read only'); }
}
var todo = new Todo({id: 123456});
console.log(todo.id); // return 123456
todo.id = 654321; // throw error
console.log(todo.id); // return 123456
The problem with this is that we cannot even change the value from within the class.
class Todo {
#data
constructor(data) {
this.#data = data
}
get findData() {
return this.#data;
};
set findData(value) {
throw new Error("Todo findData property readonly")
}
}
const newTodo = new Todo({
id: 1,
name: "lorem",
description: "lorem ipsum"
});
newTodo.findData = {
id: 2,
name: "lorem 2",
description: "lorem ipsum 2"
}
console.log(newTodo.findData);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty useful, thank you!
I thought setting a
readOnly
private property with just the getter would avoid the need to write the setter. In case anyone else is wondering about this, TypeScript would fail to compile if trying to access a private property even when there's a getter with that same name. So, yep, the setter is necessary.