gpt4 book ai didi

typescript - Typescript 类中的 Node-ipc

转载 作者:行者123 更新时间:2023-12-04 14:21:15 25 4
gpt4 key购买 nike

我正在尝试在我的 TypeScript 项目中使用 node-ipc 并坚持为类成员获取正确的类型:

import { IPC } from 'node-ipc';

class IpcImpl extends IIpc {
ipcSocketPath?: string;
ipc?: any; // What the type should be here?


setupIpc(ipcSocketPath: string) {
this.ipcSocketPath = ipcSocketPath;
this.ipc = new IPC(); // Here instantiated ok, but type mismatch ed

}

我当然安装了 @types/node-ipc 但它对我没有帮助。我试图指定以下内容(一切都不正确):

  • ipc?: IPC
  • ipc?: typeof IPC

如何正确指定我的ipc类成员的类型?

最佳答案

从node-ipc的index.d.ts内容来看,不能使用NodeIPC命名空间或 NodeIPC.IPC直接类,因为它们不导出:

declare namespace NodeIPC {
class IPC {
// Some methods
}
// Some other classes
}

declare const RootIPC: NodeIPC.IPC & { IPC: new () => NodeIPC.IPC };

export = RootIPC;

但是,如果您使用的是 TypeScript 2.8+,由于条件类型类型推断,您应该能够推断类型> 在你的案例中使用:

type InferType<T> = T extends new () => infer U ? U : undefined;

所以你可以获得NodeIPC.IPC输入:

import { IPC } from 'node-ipc';

type InferType<T> = T extends new () => infer U ? U : undefined;

class IpcImpl {

ipcSocketPath?: string;
ipc?: InferType<typeof IPC>;

setupIpc(ipcSocketPath: string) {
this.ipcSocketPath = ipcSocketPath;
this.ipc = new IPC();
}

}

您可以在 TypeScript 2.8 发行说明中找到有关条件类型和类型推断的一些有趣信息: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html

更新:

我刚刚发现 TypeScripts 的 2.8+ 包括 InstanceType<T>InferType<T> 完全相同的预定义条件类型从我上面的代码。所以实际上,直接使用它,我们有一个更短的解决方案:

class IpcImpl {

ipcSocketPath?: string;
ipc?: InstanceType<typeof IPC>;

setupIpc(ipcSocketPath: string) {
this.ipcSocketPath = ipcSocketPath;
this.ipc = new IPC();
}

}

关于typescript - Typescript 类中的 Node-ipc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54572361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com