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?
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.
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.
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.
Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With