vendredi 29 mars 2019

Define argument type in function body of decorator

The following decorator takes a function argument called func. The func will be executed within the returned function of the decorator - with an argument that's depending on the type of the property the decorator was called upon.

type ArgumentFunc = <T>(arg: T) => T;

function Decorator(func: ArgumentFunc): PropertyDecorator {
    return (prototype, field) => {
        const designType: string | number = Reflect.getMetadata('design:type', prototype, field);
        func<typeof designType>(designType);
    }
}

class Foo {
    @Decorator(string => string) // string is of type T, should be type string
    bar: string;

    @Decorator(number => number) // string is of type T, should be type number
    baz: number;
}

Can the argument of func be described when its type depends on the parent functions execution?





Aucun commentaire:

Enregistrer un commentaire