Reputation: 10028
I am trying to use node-ipc
in my TypeScript project and stuck on getting correct type for class member:
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
}
I of course installed @types/node-ipc
but it doesn't helped me. I tried to specify following (everything incorrect):
ipc?: IPC
ipc?: typeof IPC
How to specify type of my ipc
class member right?
Upvotes: 3
Views: 987
Reputation: 313
From the node-ipc's index.d.ts content, you can not use the NodeIPC
namespace or NodeIPC.IPC
class directly as they are not exported:
declare namespace NodeIPC {
class IPC {
// Some methods
}
// Some other classes
}
declare const RootIPC: NodeIPC.IPC & { IPC: new () => NodeIPC.IPC };
export = RootIPC;
But, if you are using TypeScript 2.8+, you should be able to infer the type thanks to the conditional types and the type inference using in your case:
type InferType<T> = T extends new () => infer U ? U : undefined;
And so you can get the NodeIPC.IPC
type:
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();
}
}
You can find some interresting information about the conditional types and type inference in the TypeScript 2.8 release notes: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html
Update:
I just found out that TypeScripts's 2.8+ includes the InstanceType<T>
predefined conditional type which does exactly the same thing than the InferType<T>
from my code above.
So in fact, use it directly and we have an even shorter solution:
class IpcImpl {
ipcSocketPath?: string;
ipc?: InstanceType<typeof IPC>;
setupIpc(ipcSocketPath: string) {
this.ipcSocketPath = ipcSocketPath;
this.ipc = new IPC();
}
}
Upvotes: 3