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

TypeScript中如何实现函数参数类型依赖于另一参数?

解决TypeScript泛型函数中类型不匹配问题

你的代码里泛型参数T虽然关联了type和value的类型,但在分支判断中,TypeScript无法将泛型T与具体的FilterType成员做精确收窄,导致value仍被识别为string | number | Date联合类型,无法直接赋值给filters的具体属性。

最优解决方案:使用索引直接赋值

不需要冗余的分支判断,直接通过索引访问赋值,TypeScript能自动识别类型匹配:

enum FilterType {
    userId = 'userId',
    date = 'date',
    section ='section'
}

type FilterValueType = {
    [FilterType.userId]: string;
    [FilterType.date]: Date;
    [FilterType.section]: number;
};

const filters = {} as FilterValueType;

function setFilter<T extends FilterType>(type: T, value: FilterValueType[T]) {
    // 直接通过索引赋值,类型自动匹配
    filters[type] = value;
}

若需保留分支判断:添加类型断言

如果业务逻辑需要分支处理额外逻辑,可以在每个分支中对value做精确的类型断言:

function setFilter<T extends FilterType>(type: T, value: FilterValueType[T]) {
    if (type === FilterType.userId) {
        filters.userId = value as FilterValueType[FilterType.userId];
    }
    if (type === FilterType.date) {
        filters.date = value as FilterValueType[FilterType.date];
    }
    if (type === FilterType.section) {
        filters.section = value as FilterValueType[FilterType.section];
    }
}

原理说明

第一种方案利用了TypeScript的索引访问类型特性:filters[type]的类型会被推导为FilterValueType[T],与参数value的类型完全一致,因此不会出现类型不匹配错误。分支判断的方案则通过类型断言明确告诉编译器当前分支中value的具体类型,绕过类型检查的限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 10:17:07