Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use decorator to add meta data to interface properties

Is it possible to use decorators to mark certain properties of an interface with some custom info?

Best explained with an example:

App state interface:

export interface AppState {
    @persist userData: UserData,
    @persist selectedCompany: UserCompany,

    // userCompanies should not be persisted since they are always
    // fetched afresh from the server...
    userCompanies: UserCompany[]
}

Method which persists all relevant state info:

persistState(state) {
    let newState = {};

    Object.keys(state).forEach((key) => {
        if (state[key] is decorated with @persist) {
            newState[key] = state[key];
        }
    });

    // Persist newState...
}

Is this possible?
If so, I'd really appreciate some resources to point me in the right direction!
If not, are there any elegant alternatives?

like image 482
suamikim Avatar asked Mar 09 '17 15:03

suamikim


People also ask

What is the use of decorators in TypeScript?

Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript. NOTE Decorators are an experimental feature that may change in future releases.

What is target in decorator TypeScript?

The first parameter is commonly called target . The sealed decorator will be used only on class declarations, so your function will receive a single parameter, the target , which will be of type Function . This will be the constructor of the class that the decorator was applied to.

What is decorator in node JS?

A decorator (also known as a decorator function) can additionally refer to the design pattern that wraps a function with another function to extend its functionality. This concept is possible in JavaScript because of first-class functions — JavaScript functions that are treated as first-class citizens.

Does TypeScript support interface?

Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.


1 Answers

Is it possible to use decorators to mark certain properties of an interface with some custom info

No. Interfaces cannot be used with decorators as decorators work on top of things that actually exist at runtime. (Interfaces are erased).

like image 170
basarat Avatar answered Oct 24 '22 15:10

basarat