ค้นหาเว็บไซต์

Node-ipc ในคลาส Typescript


ฉันกำลังพยายามใช้ 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?: IPC
  • ipc?: typeof IPC

จะระบุประเภทของสมาชิกคลาส ipc ของฉันอย่างถูกต้องได้อย่างไร?

คำตอบ #1

จากเนื้อหา index.d.ts ของ node-ipc คุณไม่สามารถใช้ namespace 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+ คุณควรสามารถสรุปประเภทได้โดยขอบคุณ conditional types และ type inference ที่ใช้ในกรณีของคุณ:

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

อัปเดต:

ฉันเพิ่งพบว่า TypeScript เวอร์ชัน 2.8 ขึ้นไปมีประเภทเงื่อนไขที่กำหนดไว้ล่วงหน้า InstanceType<T> ซึ่งทำสิ่งเดียวกันกับ InferType<T> จากโค้ดของฉันข้างต้น ดังนั้นในความเป็นจริง ใช้มันโดยตรงแล้วเราจะได้วิธีแก้ปัญหาที่สั้นกว่าด้วย:

class IpcImpl {

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

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

}