Decorating methods

Let's assume that we want to make a method on a class read-only. Therefore, after creating the method, it cannot be overridden for any reason. For example, this is what the method looks like:

class Report {  errPayload;  // To become readonly  error() {     console.log(`The following error occured ${errPayload}`)  }}

If we do not want to override error in the application's lifecycle, we could write a decorator to set the descriptor's writable property to false:

function readonly(target, key, descriptor) {   descriptor.writable = false;   return descriptor}

The common signature is that a method decorator takes the same parameters as Object.defineProperty. In such a case, the target will be the class, the key will be the method name, ...

Get TypeScript 2.x for Angular Developers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.