site infoHacknerd | Tech Blog
blog cover

🏢 [TypeScript] 函数签名重载

Typescript

发现问题

函数需要根据不同入参,返回不同类型的返回值。

解决方案

发现可以通过TS重载函数进行解决

image

参考地址

Clas实现

可以实现根据DeviceType 来返回对应的service 。如当type = DeviceType.a 时返回A服务,type =DeviceType.b 时返回B服务。

typescriptCopy
export enum DeviceType {
	a,
	b,
	c,
	d
}

class TestReload {
  public getService(type?: DeviceType.a): ServiceA
  public getService(type?: DeviceType.b): ServiceB
  public getService(type?: DeviceType.c): ServiceC
  
  public getService(type?: DeviceType) {
    switch (type) {
      case DeviceType.a:
        return this.hanwangService_;
      case DeviceType.b:
        return this.qixingService_;
      case DeviceType.c:
        return this.bjCaService_;
      default:
        throw new Error('未找到服务');
    }
  }
}

// 使用
const instance = new TestReload()
const aService = instance.getService(DeviceType.a)
const bService = instance.getService(DeviceType.b)
const cService = instance.getService(DeviceType.c)

函数实现

typescriptCopy
function getService(type?: DeviceType.a): ServiceA
function getService(type?: DeviceType.b): ServiceB
function getService(type?: DeviceType.c): ServiceC

function getService(type?: DeviceType) {
  switch (type) {
    case DeviceType.a:
      return this.hanwangService_;
    case DeviceType.b:
      return this.qixingService_;
    case DeviceType.c:
      return this.bjCaService_;
    default:
      throw new Error('未找到服务');
  }
}

const aService = getService(DeviceType.a)
const bService = getService(DeviceType.b)
const cService = getService(DeviceType.c)

Contents

  • 发现问题
  • 解决方案
  • 参考地址
  • Clas实现
  • 函数实现

2024/08/09 02:18