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

如何在TypeScript中让两个对象全程保持智能类型一致性?

解决方案

使用泛型让两个参数的类型绑定,这样在判断其中一个参数的类型后,另一个会自动推断为相同类型,无需额外断言。

修改后的代码如下:

type Param = number[] | Record<string, string>

function test<T extends Param>(a: T, b: T) {
    if (Array.isArray(a)) {
        // 此时a和b都被推断为number[]
        console.log(a.length, b.length); // 可直接使用数组属性
    } else {
        // 此时a和b都被推断为Record<string, string>
        console.log(Object.keys(a), Object.keys(b)); // 可直接使用对象属性
    }
}

// 测试用例
test([1,2,3], [4,5,6]); // 合法:两个参数均为number[]
test({name: "foo"}, {age: "20"}); // 合法:两个参数均为Record<string, string>
test([1,2], {name: "bar"}); // 编译报错:参数类型不匹配,符合预期

原理说明

  • 泛型T extends Param限定了T只能是Param的子类型(即number[]或Record<string, string>)。
  • 调用函数时,TypeScript会根据第一个参数自动推断出T的具体类型,第二个参数必须与T类型一致,否则编译报错。
  • 在函数内部判断a的类型时,TypeScript会基于T的类型缩小b的类型范围,实现自动推断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:30:57