Implementing this logic in JavaScript can be a bit tricky when using a single primitive value. However, you can ensure type safety by incorporating setter and getter methods. The setter method checks if the value has already been set, while the getter method retrieves it.
const customObject = (() => {
let value: number;
return {
setValue: (newValue: number) => {
if (value !== undefined) {
throw new Error('Value has already been set');
}
value = newValue;
},
getValue: () => {
if (value === undefined) {
throw new Error('Value has not been set yet');
}
return value;
}
};
})();
// will throw an error
const result1 = customObject.getValue();
// will return 3
customObject.setValue(3);
const result2 = customObject.getValue();
// will throw an error if run just after the above
customObject.setValue(5);