Sergey Stepanov Sergey Stepanov - 24 days ago 14
TypeScript Question

Typescript: enum type as decorator parameter

Is it possible to pass enum type as parameter to a decorator function?

export class A {
@AsEnum(SomeEnum)
name: string;
}

export enum SomeEnum { A, B, C}

export function AsEnum(type): any {
return (target, propert) => {
return {
get: function(): Object {
return type; // type is undefined
},
}
};
}


Here type is always undefined.

Answer

The problem is the order of your code.
If you'll do:

console.log("the enum: ", SomeEnum);
export enum SomeEnum { A, B, C}

You'll get:

the enum: undefined

You need to place the declaration of SomeEnum before using it when calling the decorator:

function AsEnum(type): any {
    return (target, propert) => {
      return {
            get: function(): Object {
                return type; // type is undefined
            },
        }
    };
}

enum SomeEnum { A, B, C}

class A {
    @AsEnum(SomeEnum)
    name: string;
}

The interpreter hasn't evaluated the enum yet when you try to use it for the decorator.

Comments