使用装饰器将元数据添加到接口属性

时间:2017-03-09 15:50:35

标签: typescript interface decorator

是否可以使用装饰器使用某些自定义信息标记界面的某些属性?

最好用一个例子解释:

应用状态界面:

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[]
}

保留所有相关州信息的方法:

persistState(state) {
    let newState = {};

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

    // Persist newState...
}

这可能吗?
如果是这样,我真的很感激有些资源可以指引我朝着正确的方向前进! 如果没有,有没有优雅的选择?

1 个答案:

答案 0 :(得分:5)

  

是否可以使用装饰器使用某些自定义信息标记界面的某些属性

没有。接口不能与装饰器一起使用,因为装饰器在运行时实际存在的东西之上工作。 (接口被删除)。