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?
From the node-ipc's index.d.ts content, you can not use the
NodeIPC
namespace orNodeIPC.IPC
class directly as they are not exported: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: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 theInferType<T>
from my code above. So in fact, use it directly and we have an even shorter solution: