You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript类方法重载:根据入参A/B类型对应返回Y/Z类型的实现方案

TypeScript类方法重载实现方案

报错原因

  1. TypeScript 要求类方法重载时,需要先在类内部显式声明重载签名,仅在接口中定义重载不会被类的实现自动继承识别,TS无法确认你写的联合类型实现和接口重载的对应关系
  2. 你的Response2定义中误用了bool,TS中正确的布尔类型是boolean,类型拼写错误也会引发类型不兼容报错
  3. 方法实现中没有对入参做类型收窄,TS无法校验返回值和入参类型的对应关系

完整可运行代码

interface Argument1 {
  argOnePropOne: string
  argOnePropTwo: string
  argOnePropThree: string
}

interface Argument2 {
  argTwoPropOne: number
  argTwoPropTwo: string
}

interface Response1 {
  responseOnePropOne: number
}

// 修正bool为boolean
interface Response2 {
  responseTwoPropOne: string
  responseTwoPropTwo: boolean
}

type UnionArg = Argument1 | Argument2
type UnionResponse = Response1 | Response2

interface xClassInterface {
  x(arg: Argument1): Response1
  x(arg: Argument2): Response2
}

class X implements xClassInterface {
  // 先在类内声明重载签名,和接口保持一致
  x(arg: Argument1): Response1
  x(arg: Argument2): Response2
  // 再写兼容所有重载的实现签名
  x(arg: UnionArg): UnionResponse {
    // 通过判断独有的属性做类型收窄
    if ('argOnePropOne' in arg) {
      // 此时TS识别arg为Argument1类型,返回Response1即可
      return {
        responseOnePropOne: 123
      }
    } else {
      // 此时TS识别arg为Argument2类型,返回Response2即可
      return {
        responseTwoPropOne: 'test',
        responseTwoPropTwo: true
      }
    }
  }
}

校验规则说明

  • 接口类型在编译后会被抹除,不能用typeof/instanceof做运行时校验,要通过判断两个入参类型的独有属性(比如argOnePropOne是Argument1独有,argTwoPropOne是Argument2独有)来做类型收窄
  • 重载签名仅用于TS类型推导,调用方法时只会匹配你声明的重载规则,不会暴露底层实现的联合类型
  • 实现签名的参数、返回值类型必须是所有重载签名的兼容超集,否则会触发类型不兼容报错

内容的提问来源于stack exchange,提问作者Brandon6

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:45:01