是否可以在 class 在 Typescript 中创建后向其添加装饰器?

Is it possible to add a decorator to a class after its creation in Typescript?

我想在创建后用 inversify 的 @injectable 装饰器更新 class;用例是我想使用像 ts-auto-mock 这样的模拟库为我创建一个模拟,然后应用 @injectable 装饰器,这样我就可以将模拟绑定到服务类型。

const mockExampleService = createMock<ExampleService>();
// I want to apply the @injectable decorator to mockExampleService here

// inversify.unit-config.ts
const container = new Container();
const.bind<ExampleService>(TYPES.ExampleService).to(mockExampleService);

好的! Inversify 正是为此目的提供了一个 decorate 函数。

const mockExampleService = createMock<ExampleService>();
decorate(injectable(), mockExampleService);

// inversify.unit-config.ts
const container = new Container();
const.bind<ExampleService>(TYPES.ExampleService).to(mockExampleService);