Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to apply a TypeScript decorator to all fields in a class?

Tags:

typescript

I've been fiddling with decorators in Typescript and I have a simple problem, suppose I have a custom decorator called RetainType and a class like this:

class Person {
    @RetainType name: string;
    @RetainType age: number;
    @RetainType dateOfBirth: Date;
}

I'd like to be able to write:

@RetainType class Person {
    name: string;
    age: number;
    dateOfBirth: Date;
}

In other words, is there any way to apply a decorator to all properties in a class? I use @RetainType to emit metadata about the individual properties (design:type specifically). It would be nice to have a more concise way of doing this than annotating all the fields one by one.

like image 856
Vladimir Rovensky Avatar asked Nov 09 '22 10:11

Vladimir Rovensky


1 Answers

Property decorator is applied to one property. It returns nothing, just do some stuff with related property.

Class decorator is applied to class constructor. So it should return function that substitutes normal constructor with some functionality.

In class decorating function you can do anything - even enumerating all class properties with decorating them in expected manner. So you can do what you want if write extra code. But you can't use property decorators as class decorators without changing them. It just wouldn't work.

like image 126
Vadim Levkovsky Avatar answered Dec 15 '22 16:12

Vadim Levkovsky