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

TypeScript如何访问索引器下嵌套类型的属性类型

TypeScript 索引签名嵌套类型访问方案

给定如下接口定义:

interface Example {
    items: {
        [k: string]: {
            name: string;
            value: {
                subName: {
                    subValue: string;
                };
            };
        };
    };
};

你可以使用string作为索引类型,访问字符串索引签名对应的通用元素类型,正确获取value对象类型的写法如下:

// 写法1:分步骤提取
type Items = Example['items'];
type ItemEntity = Items[string]; // 拿到所有索引对应的统一对象类型
type ValueType = ItemEntity['value'];

// 写法2:链式一行编写
type ValueTypeDirect = Example['items'][string]['value'];

如果需要提取更深层的subValue类型,写法同理:

type SubValueType = Example['items'][string]['value']['subName']['subValue']
// 最终得到的SubValueType类型为 string

原错误写法Example['items']['']['value']不生效的原因:''是字符串字面量类型,仅能匹配items下键为空字符串的单个属性类型,无法匹配所有索引对应的通用元素类型。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 14:45:03