有没有办法使用typescript动态添加方法?

pll*_*lee 22 typescript

我正在尝试创建某种mixin方法,它可以动态地将方法添加到原型/类中,但是我会遇到错误

属性'greetName'在类型'Greeter'any的值上不存在

属性'greetName'在类型'Greeter'any的值上不存在

当我运行以下代码时.

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

Greeter.prototype.greetName = function(name){
        return this.greet() + ' ' + name;
}

var greeter = new Greeter('Mr');

window.alert(greeter.greetName('Name'));
Run Code Online (Sandbox Code Playgroud)

它实际上编译为有效的js并按预期运行.有没有办法在编译器警告/错误的情况下执行此操作?

Fen*_*ton 16

此解决方案的好处是,在动态添加方法时为您提供类型检查:

class MyClass {
    start() {

    }
}
var example = new MyClass();
// example.stop(); not allowed


interface MyClass {
  stop(): void;
}

MyClass.prototype['stop'] = function () {
    alert('Stop');
}
var stage2 = example;
stage2.stop();
Run Code Online (Sandbox Code Playgroud)


Ste*_*man 8

他们需要一个部分类的概念来实现,目前不支持.我会告诉你,我发现对于这些类型的场景更有效的方法是使用接口(我现在已经在TypeScript中编程了大约6个月 - 我在MS但不在TypeScript团队中)

通过简单地定义您添加到接口的方法,接口在事后是可扩展的.作为一个例子,如果你安装一个jQuery插件,你将需要重新定义IJQuery和IJQueryUtil接口,以包含插件的其他方法.从那时起,您可以通过$ .plugin()调用插件方法,TypeScript会很高兴.


Jam*_*ock 8

还有另一种方法可以做到这一点.

Greeter["SomeProperty"] = function() {
     return "somevalue";
};
Run Code Online (Sandbox Code Playgroud)

工作相同并使用javascript中的属性索引器函数和打字稿不抱怨.

  • 这对于向 js 类添加静态方法非常有用,但我希望将方法添加到原型中,以便将它们视为实例函数。 (2认同)