Blog>
Snippets

Validating Object Structure with Object.defineProperty

Showcase how to enforce object property types by using Object.defineProperty with a custom setter function.
// Define a base object
const dataObject = {};

// Define property 'age' with validation in the setter
Object.defineProperty(dataObject, 'age', {
    enumerable: true,
    configurable: true,
    get: function() {
        return this._age;
    },
    set: function(value) {
        if (typeof value !== 'number') {
            throw new TypeError('Age must be a number.');
        }
        if (value < 0 || value > 150) {
            throw new RangeError('Age must be between 0 and 150.');
        }
        this._age = value;
    }
});
This code snippet adds an 'age' property to the 'dataObject' with custom getter and setter functions using Object.defineProperty. It enforces the age property to be a number and within the range of 0 to 150. If an invalid age is set, it throws a TypeError or a RangeError.
// Attempt to use the defined property
try {
    dataObject.age = 25; // Valid usage
    console.log(dataObject.age); // Outputs: 25

    dataObject.age = 'thirty'; // Invalid usage, not a number
} catch (error) {
    console.error(error.message); // Outputs the error message
}
This code snippet demonstrates how to use the 'age' property defined with Object.defineProperty on the 'dataObject'. It first sets a valid age, then tries to set an invalid age, catching and logging the error that is thrown.