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

如何消除TypeScript中通过数组键访问嵌套对象值的类型错误?

解决TypeScript遍历嵌套属性时的类型报错问题

问题分析

你遇到的错误是因为TypeScript无法确定遍历的键对应的属性类型:keyof MyType包含了a、b(对应MyRecord类型)和c、d(对应string类型),所以r[key as keyof MyType]的类型被推断为string | MyRecord,而字符串类型没有value属性,因此抛出错误。

解决方案

无需拆分原有MyType类型,只要让TypeScript明确知道遍历的键对应的都是MyRecord类型的属性即可,有两种简洁的实现方式:

方式1:用as const限定数组类型

直接通过as const让TypeScript推断出数组的具体字面量类型,明确每个键的类型:

type MyRecord={
    id:string;
    value:string;
}
type MyType={
    a:MyRecord;
    b:MyRecord;
    c:string,
    d:string,
}

const validate = (r:MyType)=>{
    // as const 让TS识别出这是["a", "b"]字面量元组
    const keys=["a","b"] as const;
    for (const key of keys){
        // TS能确定r[key]是MyRecord类型,可安全访问value
        if(r[key].value!==""){
           return false
        }
    }
    return true
}

方式2:用工具类型提取目标键

如果需要复用目标键的类型,可以先提取出MyType中值为MyRecord的键类型,再限定数组:

type MyRecord={
    id:string;
    value:string;
}
type MyType={
    a:MyRecord;
    b:MyRecord;
    c:string,
    d:string,
}

// 提取MyType中值类型为MyRecord的键
type MyRecordKeys = {
  [K in keyof MyType]: MyType[K] extends MyRecord ? K : never
}[keyof MyType];

const validate = (r:MyType)=>{
    const keys: MyRecordKeys[] = ["a","b"];
    for (const key of keys){
        if(r[key].value!==""){
           return false
        }
    }
    return true
}

原理说明

  • 方式1中,as const会将数组转换为只读的字面量元组,TypeScript能精准识别每个元素对应的属性类型,从而确定r[key]是MyRecord。
  • 方式2通过条件类型遍历MyType的所有键,筛选出值类型为MyRecord的键,让数组的类型被严格限定,避免了类型歧义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:41:05