You need to enable JavaScript to run this app. TypeScript中如何绑定两种类型实现函数入参与返回值类型对应
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何绑定两种类型实现函数入参与返回值类型对应

问题原因

你现有的写法中,泛型T是MyStringType | MyNumberType联合类型,TypeScript 无法将传入的endpoint字面量和联合类型的对应分支做关联绑定,导致T['returnType']始终被推导为string | number联合类型,所以出现赋值报错。

修复方案

方案1:基于现有类型推导映射关系(无需修改原有类型定义)

通过映射类型从你已经定义的MyStringType、MyNumberType中自动生成endpoint到返回类型的对应关系:

import axios from 'axios';

type MyStringType = { endpoint: 'myString'; returnType: string };
type MyNumberType = { endpoint: 'myNumber'; returnType: number };

// 新增:从已有类型生成映射关系
type AllEndpoint = MyStringType | MyNumberType;
type EndpointReturnTypeMap = {
  [E in AllEndpoint['endpoint']]: Extract<AllEndpoint, { endpoint: E }>['returnType']
};

// 修改泛型定义,直接绑定入参和返回值类型
function getData<T extends keyof EndpointReturnTypeMap>(endpoint: T) {
  return axios.get<EndpointReturnTypeMap[T]>(`https://my.url/${endpoint}`);
}

// 调用时类型推导正常
getData('myString').then(response => {
  const newString: string = response.data; // 类型正常
});

getData('myNumber').then(response => {
  const newNumber: number = response.data; // 类型正常
});

方案2:简化类型定义,直接声明映射关系

如果不需要保留MyStringType、MyNumberType两个类型,可以直接定义更简洁的映射关系:

import axios from 'axios';

// 直接定义endpoint和返回值的映射
type EndpointMap = {
  myString: string;
  myNumber: number;
};

function getData<T extends keyof EndpointMap>(endpoint: T) {
  return axios.get<EndpointMap[T]>(`https://my.url/${endpoint}`);
}

方案3:函数重载(适合逻辑分支复杂的场景)

如果后续还会新增更多endpoint规则,用函数重载的写法可读性更强:

import axios from 'axios';

// 声明重载签名
function getData(endpoint: 'myString'): Promise<{ data: string }>
function getData(endpoint: 'myNumber'): Promise<{ data: number }>
// 实现签名
function getData(endpoint: string) {
  return axios.get(`https://my.url/${endpoint}`);
}

内容的提问来源于stack exchange,提问作者Dan B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:57:02