【发布时间】:2021-03-13 07:25:04
【问题描述】:
我正在使用 ts 编写一个库,在尝试扩展核心模块类型时遇到了一些麻烦。这是项目结构。
- src
- core
- core.ts
- plugins
- insert
- index.ts
core.ts中的代码
export interface Commands {}
export class Core {
commands: Commands;
constructor() {
this.commands = {};
}
registerCommands(name: string, func: any) {
// @ts-ignore
this.commands[name] = func;
}
}
insert/index.ts中的代码
import { Core } from "../../core/core";
export class InsertPlugin {
constructor(core: Core) {
core.registerCommands("insert", this.insert.bind(this));
}
insert(value: string) {
console.log("insert " + value);
}
}
InsertPlugin 使用core.registerCommands 将命令insert 注册到核心。
我的问题是使用我的库的人如何获取insert 命令的类型。例如
// assume the name of the library is core
import { createCore } from 'core'
const core = createCore()
// How can i get types for insert method
core.commands.insert()
我已经为上面的代码创建了一个完整的演示,https://github.com/clinyong/ts-extends-core-commands。
我还阅读了插件类型的 typescript 手册,https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-plugin-d-ts.html。
【问题讨论】:
标签: typescript