You need to enable JavaScript to run this app. 为什么TypeScript中用字符串索引读属性合法,赋值却报错?
优惠活动
大模型
产品
解决方案
定价
更多

为什么TypeScript中用字符串索引读属性合法,赋值却报错?

TypeScript 泛型对象索引读写校验差异问题

需求说明

遍历两个类型相同的未知类型对象,在尽可能不使用类型断言的前提下,将二者number类型的同名属性相加。

问题复现

相关代码如下:

const a = {x:1, y:1, z:1};
const b = {x:2, y:2, z:2};

function reduceObjects<T extends {[key: string]: any}>(currentValue: T, previousValue: T): T {
    const result = Object.assign({}, previousValue) as T;

    for (const key of Object.keys(result)) {
        const prev = result[key];
        //           ^^^^^^^^^^^ 此处读取属性正常
        const curr = currentValue[key];
        if (typeof prev === "number" && typeof curr === "number") {
            result[key] = prev + curr;
        //  ^^^^^^^^^^^ 此处赋值报错
        //                 错误信息:*"Type 'string' cannot be used to index type 'T'.(2536)"*
        } else if (typeof prev === "string" && typeof curr === "string") {
            result[key] = prev + curr;
        //  ^^^^^^^^^^^ 此处同样触发报错
        }
    }

    return result;
}

const c = reduceObjects(a, b);

核心疑问

为什么同样的string类型的key,作为索引读取泛型对象属性可以通过校验,作为索引赋值时就会触发类型错误?希望了解该错误出现的根本原因,而非代码修复方案。

版本差异

该代码在TypeScript v3.3版本中可以正常运行,从v3.5版本开始才会触发该错误。

内容的提问来源于stack exchange,提问作者T.J. Crowder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 23:24:05