TypeScript-Handbook icon indicating copy to clipboard operation
TypeScript-Handbook copied to clipboard

@classDecorator example in Decorators chapter is confusing

Open HubertKauker opened this issue 8 years ago • 1 comments

The Decorators chapter of the TypeScript handbook has an example with a @classDecorator. When the example is run in Nodejs, the following is output:

class_1 { property: 'property', hello: 'override', newProperty: 'new property'}

This is confusing. The expected output would be:

Greeter { property: 'property', hello: 'override', newProperty: 'new property'}

In order to achieve this, one has to change the classDecorator function. The returned constructor function needs an explicit name copied from the original constructor.

Current Version:

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    return class extends constructor {
        newProperty = "new property";
        hello = "override";
    }
}

Better:

function classDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
    let fn = class extends constructor {
        newProperty = "new property";
        hello = "override";
    };
    Object.defineProperty(fn, "name", { value: (constructor as any).name });
    return fn;
}

HubertKauker avatar Oct 10 '17 21:10 HubertKauker

Better yet, create a self-documenting interface/type to abstract away that <T extends {new(...args:any[]): {}}>(constructor: T) signature.

Seems an abruptly esoteric bit of syntax to drop in there without explanation.

slimlime avatar Jul 17 '18 06:07 slimlime