Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Typescript:使用decorator时的类型推断_Javascript_Oop_Typescript_Decorator - Fatal编程技术网

Javascript Typescript:使用decorator时的类型推断

Javascript Typescript:使用decorator时的类型推断,javascript,oop,typescript,decorator,Javascript,Oop,Typescript,Decorator,我想知道为什么在类的Typescript中使用装饰器或注释。编译器无法推断类的新类型。如果我不使用decorator,并且在ES5中使用旧的方法(即手动调用decorator),那么它显然是有效的 例如,下面是一个显示问题的示例: function decorate(Target: typeof Base): IExtendedBaseConstructor { return class extends Target implements IExtendedBase { public

我想知道为什么在类的Typescript中使用装饰器或注释。编译器无法推断类的新类型。如果我不使用decorator,并且在ES5中使用旧的方法(即手动调用decorator),那么它显然是有效的

例如,下面是一个显示问题的示例:

function decorate(Target: typeof Base): IExtendedBaseConstructor {
  return class extends Target implements IExtendedBase {
    public extendedtMethod(): number {
      return 3;
    }
  };
}

interface IBase {
  baseMethod(): number;
}

interface IExtendedBase extends Base {
  extendedtMethod(): number;
}

interface IExtendedBaseConstructor {
  new(): IExtendedBase;
}

@decorate
class Base implements IBase {
  public baseMethod(): number {
    return 5;
  }
}

const test = new Base();
test.baseMethod(); // OK
test.extendedtMethod(); // NOT OK, typescript think, Base is still Base but we decorated it.
使用旧方法,它可以工作:

class Base implements IBase {
  public baseMethod(): number {
    return 5;
  }
}

const ExtendedBase = decorate(Base);

const test = new ExtendedBase();
test.baseMethod(); // OK
test.extendedtMethod(); // OK

提前谢谢。

现在这不起作用。github上有一个允许类装饰器更改类类型的命令


我建议您在实现之前使用您提到的“旧方法”。

此模式的优点是什么?是不是更容易理解?你是对的。在这种情况下,这种模式是无用的。但是新的前端框架(比如angular2)选择使用decorator而不是继承来声明新组件。我已经编写了一个库,向用户建议一个助手来创建类API(其中注入了一些参数和有用的方法)。因此,我创建了一个提供功能的抽象Api类和一个装饰器,该装饰器通过
元数据
将Api注册到我的框架中。在这种情况下,我的用户必须执行:
import{AbstractAPI,Api}from'myLib'@Api(…)类UserApi扩展了AbstractAPI{}
。如果我可以删除扩展并将所有内容合并到我的decorator
@Api
,它将减少最终的用户输入错误。哦,我明白了。谢谢我很好奇。