Typescript 如何扩展其他模块';打字脚本中的字符类型
我正在使用ts编写一个库,在尝试扩展核心模块类型时遇到了一些麻烦。这是项目结构Typescript 如何扩展其他模块';打字脚本中的字符类型,typescript,Typescript,我正在使用ts编写一个库,在尝试扩展核心模块类型时遇到了一些麻烦。这是项目结构 - src - core - core.ts - plugins - insert - index.ts 核心.ts中的代码 export interface Commands {} export class Core { commands: Commands; constructor() { this.commands = {}; } regist
- src
- core
- core.ts
- plugins
- insert
- index.ts
核心.ts中的代码
export interface Commands {}
export class Core {
commands: Commands;
constructor() {
this.commands = {};
}
registerCommands(name: string, func: any) {
// @ts-ignore
this.commands[name] = func;
}
}
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);
}
}
在insert/index.ts中输入代码
export interface Commands {}
export class Core {
commands: Commands;
constructor() {
this.commands = {};
}
registerCommands(name: string, func: any) {
// @ts-ignore
this.commands[name] = func;
}
}
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
向core注册命令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()
我已经为上述代码创建了一个完整的演示
此外,我还阅读了插件类型的typescript手册。您的示例有趣的是,只有在您创建了一个新的InsertPlugin(core)
实例(您在示例中没有这样做)之后,访问core.commands.insert()
才有效
有鉴于此,如果要使用断言返回类型的函数,而不是类,那么实际上可以对该需求进行编码
insert/index.ts
:
import { Core } from "../../core/core";
function registerInsertPlugin(core: Core): asserts core is (Core & {
commands: {
insert: typeof insert
}
}) {
const insert = (value: string) => {
console.log("insert " + value);
}
core.registerCommands("insert", insert);
}
然后你可以这样使用它:
import { createCore } from 'core'
import { registerInsertPlugin } from 'insert'
const core = createCore();
registerInsertPlugin(core);
core.commands.insert('hello world');
忘记调用registerInsertPlugin将导致有效类型错误:
import { createCore } from 'core'
const core = createCore();
core.commands.insert('hello world');
// ^ Property 'insert' does not exist on type 'Commands'
除此之外,您还可以创建多个“插件”,每个插件都将扩展core
const core = createCore();
registerInsertPlugin(core);
registerUpsertPlugin(core);
core.commands.insert('hello world');
core.commands.upsert("hello world");
/* Resulting Type:
* const core: Core & {
* commands: {
* insert: (value: string) => void;
* };
* } & {
* commands: {
* upsert: (value: string) => void;
* };
* }
*/