RecipesChapter 9: The Standard Library and External Type Definitions

Working with defineProperty

Recipe 9.3 from The TypeScript Cookbook


const storage = {
  currentValue: 0
};

defineProperty(storage, 'maxValue', { 
  writable: false, value: 9001 
});

storage.maxValue; // it's a number
storage.maxValue = 2; // Error! It's read-only

const storageName = 'My Storage';
defineProperty(storage, 'name', {
  get() {
    return storageName
  }
});

storage.name; // it's a string!

// it's not possible to assign a value and a getter
defineProperty(storage, 'broken', {
  get() {
    return storageName
  },
  value: 4000
});

// storage is never because we have a malicious 
// property descriptor
storage;
Open in TypeScript Playground →