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

如何让TypeScript从传入参数类型推导泛型参数值?

TypeScript泛型参数推导与返回值类型设定方案

你的核心需求是让ResultType从传入foo的参数中自动推导,并基于该类型设定函数返回值。原代码无法实现的原因是泛型参数的声明顺序和约束逻辑导致TypeScript无法反向推导ResultType,以下是两种可行方案:

方案一:简化泛型参数(适合无额外属性场景)

直接将参数类型指定为Param<ResultType>,只保留ResultType作为泛型参数,TypeScript会自动从bar属性的值推导ResultType:

type Param<Result> = { bar: Result };

// 仅声明ResultType泛型,参数类型绑定到Param<ResultType>
function foo<ResultType>(value: Param<ResultType>): ResultType {
  return value.bar;
}

// 调用时自动推导ResultType为string,返回值类型为string
const result = foo({ bar: "foo" });

方案二:使用infer提取类型(支持额外属性)

如果需要允许参数是Param的子类型(比如包含额外属性),可以通过infer关键字从参数类型中提取Result类型,无需显式声明ResultType:

type Param<Result> = { bar: Result };

// 工具类型:从Param的子类型中提取Result类型
type ExtractResult<T> = T extends Param<infer R> ? R : never;

// 泛型仅约束参数为Param的子类型,返回值类型自动提取Result
function foo<ParamType extends Param<any>>(value: ParamType): ExtractResult<ParamType> {
  return value.bar;
}

// 允许参数包含额外属性,同时推导返回值类型为string
const result = foo({ bar: "foo", extra: 123 });

原代码问题解析

原代码中同时声明了ResultType和ParamType两个泛型参数,TypeScript会优先推导ParamType为传入的{ bar: string },再检查它是否满足extends Param<ResultType>。由于ResultType未被明确约束,编译器会默认将其设为unknown(因为{ bar: string }确实符合Param<unknown>的约束),导致无法得到预期的推导结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:05:31