typescript 高阶函数的方法重载

pdtvr36n  于 2022-12-24  发布在  TypeScript
关注(0)|答案(1)|浏览(138)

目标是使用方法重载来构建开发人员友好的SDK。serviceType参数工作正常,但onMessage参数不工作。TypeScript是否不支持此功能?如果是,是否有解决方法?

type SwitchMessage = {
  propA: string;
};

type OutletMessage = {
  propB: string;
};

type ServiceType = "Switch" | "Outlet";
type ServiceMessage = SwitchMessage | OutletMessage;

class Client {
  subscribe(serviceType: "Switch", onMessage: (msg: SwitchMessage) => void);
  subscribe(serviceType: "Outlet", onMessage: (msg: OutletMessage) => void);
  subscribe(serviceType: ServiceType, onMessage: (msg: ServiceMessage) => void) {
    console.log("Hello")
  }
}

来自编译的消息:

This overload signature is not compatible with its implementation signature.
pkwftd7m

pkwftd7m1#

|处理函数参数的方式与您想象的 * 相反 *
Playground

type SwitchMessage = {
  propA: string;
};

type OutletMessage = {
  propB: string;
};

type ServiceType = "Switch" | "Outlet";
type ServiceMessage = SwitchMessage | OutletMessage;

class Client {
  subscribe(serviceType: "Switch", onMessage: (msg: SwitchMessage) => void): void;
  subscribe(serviceType: "Outlet", onMessage: (msg: OutletMessage) => void): void;
  subscribe(serviceType: ServiceType, onMessage: (msg: SwitchMessage & OutletMessage) => void) {
    console.log("Hello")
  }
  
  subscribe2(serviceType: "Switch", onMessage: (msg: SwitchMessage) => void): void;
  subscribe2(serviceType: "Outlet", onMessage: (msg: OutletMessage) => void): void;
  subscribe2(serviceType: ServiceType, onMessage: ((msg: SwitchMessage) => void) | ((msg: OutletMessage) => void)) {
    console.log("Hello")
  }
}

相关问题