【问题标题】:Can I make a class in Typescript that implements an interface, and it's still able to have decorators on it?我可以在 Typescript 中创建一个实现接口的类,并且它仍然可以有装饰器吗?
【发布时间】:2020-04-16 06:11:57
【问题描述】:

我可以在 Typescript 中创建一个实现接口的类,并且它仍然可以有装饰器吗?

我有一个班级 foo

@MyDecoratorA()
export default class Foo {
    @MyDecoratorB()
    public mySearchFunc(source: string, subString: string) {

        /*a lot of logic here*/
       return true;
    }
}

我有我的界面

  interface SearchFunc {
    (source: string, subString: string): boolean;
  }

我可以像这样创建实现 myInterface 的函数:

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    let result = source.search(subString);
    return result > -1;
}

typescript reference

我正在尝试让类“Foo”的 mySearchFunc 方法实现接口“myInterface”,但不会丢失装饰器

我以后会需要这个装饰器。

【问题讨论】:

    标签: typescript decorator


    【解决方案1】:

    您可以将类Foo上的mySearchFunc方法的声明替换为字段声明,其中字段的类型是接口,并将方法实现分配给该字段:

    interface SearchFunc {
      (source: string, subString: string): boolean;
    }
    
    @MyDecoratorA()
    export default class Foo
    {
        @MyDecoratorB()
        public mySearchFunc : SearchFunc = (source: string, subString: string) => {
    
            /*a lot of logic here*/
           return true;
        }
    }
    
    
    var foo = new Foo();
    // You can use the field the same way as if it was declared as method
    foo.mySearchFunc("a", "b");
    

    除了箭头函数() => {},您还可以使用function 表示法:

    @MyDecoratorA()
    export default class Foo
    {
        @MyDecoratorB()
        public mySearchFunc : SearchFunc = function(source: string, subString: string) {
    
            /*a lot of logic here*/
           return true;
        }
    }
    

    【讨论】:

    • @AlexSilva 不客气。如果有帮助,请随时投票 ;-)
    • 我没有足够的声望来投票:(当我得到它时,我会回来这里投票
    猜你喜欢
    • 2018-04-08
    • 1970-01-01
    • 2014-08-28
    • 2012-03-30
    • 2020-08-09
    • 2011-05-18
    • 1970-01-01
    • 2010-10-13
    • 2017-05-25
    相关资源
    最近更新 更多