嵌套类上的typescript装饰器

时间:2018-01-11 15:54:05

标签: typescript decorator

如何在嵌套类中装饰属性?这是一个例子:

    function log(name: string = 'DecoratedProp') {
        return function logHandler(target: any, field: any) {
            // get the key
            Object.defineProperty(target, field, {
                get() {
                    console.info('Accessing:' + name, field)
                    return this[name];
                },
                set(value: any): void {
                    console.warn('Setting:' + name, field)
                    this[name] = value;
                }
            })
        };
    }
    class Nested {
        @log('Nested') data: string;
    }
    export class DecoratedModel {
        nested: Nested = {
            data: 'something',
            // decorating here won't work, e.g.
            // @log() somethingElse; -> breaks
        };
        @log() topLevel: string = '33';
    }
    const deco = new DecoratedModel();
    console.log(deco.topLevel);         // logs stuff
    console.log(deco.nested.data);      // doesn't log

为什么我的嵌套属性没有装饰?

1 个答案:

答案 0 :(得分:1)

因为你正在分配一个与类接口匹配的静态对象,它满足编译器,但是没有装饰原型,因为它实际上并不是你装饰的类的实例

您需要将Nested课程与new进行实例化,然后才会有效...

class Nested {
  @log('Nested') data: string;

  constructor(data: string) {
    this.data = data
  }
}

export class DecoratedModel {
  nested: Nested = new Nested('something');

  @log('toplevel') topLevel: string = '33';
}

const deco = new DecoratedModel();
console.log(deco2.topLevel); // logs
console.log(deco2.nested.data); // also logs!