Skip to content

FlashcardNot attempted

Decorators

Recall it before you reveal

What is a class decorator, and how would one log every method call?

Space to reveal
Show answer & explanation

A decorator is a function applied with @name that receives the class (or method/field) and can return a replacement. A class decorator can return a subclass whose constructor wraps each prototype method:

function LogMethodCalls<T extends new (...a: any[]) => {}>(Base: T) {
return class extends Base { /* wrap methods from Base.prototype */ };
}

TS 5 implements the standard (stage 3) decorators; older code uses experimentalDecorators. Angular, NestJS and MobX lean on them heavily.