如何确保装饰者的论点"目标"在typescript中扩展一个接口?

时间:2017-04-23 08:12:40

标签: typescript interface decorator

我学习打字稿2并玩弄装饰和通用T. 类装饰器是否可以确保其目标扩展到特定的接口?

像这样(这段代码不起作用):

interface IAction {}

function Action(options?:any) {
    return function(target:<T extends IAction>) {}
}

@Action()
export class CreateTodoAction implements IAction {}

1 个答案:

答案 0 :(得分:1)

interface Action {
  kind: string;
}

function action(options?: {}) {
    return function<T extends new(...args: {}[]) => Action>(target: T) {}
}

@action()
export class CreateTodoAction implements Action {
  kind = 'create';
}

值得注意的是,由于implements子句在TypeScript中是可选的,并且由于装饰器强制其目标类创建满足接口的实例,因此没有真正的理由在类定义本身中使用它。只是风格问题,但感觉重复。