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

TypeScript如何实现第二个泛型从第一个泛型自动推断

问题原因

当前泛型定义里SequenceItem = T只是设置了默认值,没有加类型绑定,TypeScript不会校验SequenceItem和T的兼容性,才会抛出*'SequenceItem' could be instantiated with an arbitrary type which could be unrelated to 'T'*的错误。

修复方法

给SequenceItem加上extends T的泛型约束,去掉冗余的默认值设置即可。TypeScript会先从入参a、b推导出泛型T,再自动约束sequence的数组成员类型必须和T兼容,修改后的完整代码:

const SORT_VALUES = {
    a: -1,
    b: 1,
} as const
type sortWrapperReturn = -1 | 1 | 0
export const sortWrapper = <T extends string, SequenceItem extends T>({
    a,
    b,
    sequence,
}: {
    a: T
    b: T
    sequence?: SequenceItem[]
}): sortWrapperReturn => {
    if (a === b) return 0

    if (sequence) {
        const aIndex = sequence.indexOf(a)
        const bIndex = sequence.indexOf(b)

        if (aIndex === -1) return SORT_VALUES.b
        if (bIndex === -1) return SORT_VALUES.a

        if (aIndex > bIndex) return SORT_VALUES.b
        if (aIndex < bIndex) return SORT_VALUES.a
    }

    return 0
}
类型约束效果
  • 传入a、b后,sequence数组只能传入和a、b同类型的成员,传入无关类型会直接触发类型报错
  • 不需要手动传入泛型参数,全链路类型自动推导
  • 原有运行逻辑完全不变,没有额外侵入性

如果需要兼容sequence成员是T的父类型的场景,可以把泛型定义改成SequenceItem extends T = T,保留默认值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 13:09:16