Object.defineProperty adds a property to an existing object using a descriptor. It can create getters and setters, or define data properties with specific behavior. section 9.1.1 section 9.1.2
Listing 9.2 Defining getters and setters dynamically
interface NinjaCollection { #A
ninjas: string[]; #A
firstNinja: string; #A
} #A
const ninjaCollection = { #B
ninjas: ["Yoshi", "Kuma", "Hattori"], #B
} as NinjaCollection; #B
Object.defineProperty(ninjaCollection, "firstNinja", { #C
get() { #C
console.log(`Getting firstNinja: ${this.ninjas[0]}`); #C
return this.ninjas[0]; #C
}, #C
set(newNinja: string) { #C
console.log(`Setting firstNinja: ${newNinja}`); #C
this.ninjas[0] = newNinja; #C
}, #C
}); #C
This defines firstNinja dynamically: reading or assigning the property accesses the first item in ninjas. section 9.1.1
Descriptor options affect how a property behaves:
- Properties created this way are non-enumerable by default, so common enumeration and copying operations omit them. Set enumerable: true to include them. section 9.1.2
- A getter-only property can’t be assigned to; a setter-only property accepts values but reads as undefined. section 9.1.2
- The configurable option allows a property to be deleted; a value descriptor can define a data property. section 9.1.2
// Object from Listing 9.1 Object.keys(ninjaCollection) > [ 'ninjas', 'firstNinja' ] // Object from Listing 9.2 Object.keys(ninjaCollection) > [ 'ninjas' ]
Compare Object.keys results to see how a property added with Object.defineProperty differs from one defined in an object literal. section 9.1.2
Use Object.defineProperty when a property must be added after object creation or needs behavior such as validation, logging, or a computed value. Its descriptor syntax is more verbose than object-literal getter and setter syntax. section 9.1.1


