本文介绍了不存在带有装饰器类型的 Typescript 添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个向类添加方法的装饰器.

I want to create a decorator that adds a method to a class.

export function Deco() {
  return function<T extends { new (...args: any[]): {} }>(constructor: T) {
    constructor.prototype.someMethod = function() {

    };
  };
}


@Deco()
class Test {

}

问题是当我尝试调用添加的方法时,出现打字稿错误:

The problem is when I'm trying to invoke the added method, I am getting typescript error:

属性 someMethod 在类型 Test 上不存在.

const test = new Test();

test.someMethod();

我该如何解决这个问题?

How can I solve this issue?

推荐答案

装饰器不能影响类型的结构.对此有一个简单的解决方法.使用类调用装饰器,并在函数内部使用您想要的方法创建派生类.函数的结果将是新的装饰"类,它将拥有所有方法:

Decorators can't influence the structure of the type. There is a simple workaround to this. Invoke the decorator with the class, and inside the function create a derived class with the methods you want. The result of the function will the new "decorated" class and it will have all the methods:

export function Deco() {
    return function <T extends { new(...args: any[]): {} }>(constructor: T) {
        return class extends constructor {
            someMethod() {

            }
        }
    };
}


let Test = Deco()(class {
    // Other stuff
});

const test = new Test();
test.someMethod();

这篇关于不存在带有装饰器类型的 Typescript 添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:23