我试图在我的node-ipc项目中使用TypeScript,并坚持为类成员获取正确的类型:
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?: IPCipc?: typeof IPC如何指定我的ipc类成员的类型?
发布于 2019-02-07 14:31:11
从节点-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
更新:
我刚刚发现,类型脚本的2.8+包括InstanceType<T>预定义的条件类型,它与上面代码中的InferType<T>完全相同。因此,实际上,直接使用它,我们有一个更短的解决方案:
class IpcImpl {
ipcSocketPath?: string;
ipc?: InstanceType<typeof IPC>;
setupIpc(ipcSocketPath: string) {
this.ipcSocketPath = ipcSocketPath;
this.ipc = new IPC();
}
}https://stackoverflow.com/questions/54572361
复制相似问题