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

如何在TypeScript中定义同时包含字符串索引与指定属性的类型?

解决TypeScript中“类型为boolean的属性'pending'无法赋值给字符串索引类型”错误

错误原因

TypeScript的索引签名规则明确:所有显式声明的属性类型,必须是索引签名类型的子集。比如你定义customType时,字符串索引签名要求所有属性的值都是{ id: string },但pending是boolean类型,不符合索引签名的类型约束,因此报错。

你的另外两段尝试代码也存在问题:

  • myObj31的MyObj类型定义完全偏离需求,它要求每个键对应的值是包含自身键的对象+btnWrap属性,和你需要的结构不匹配。
  • myObj32的InnerObj索引签名是string | boolean,但key1、key2是对象类型,超出了索引签名的类型范围,同样触发错误。

修复方案

根据你的需求(一个包含pending布尔属性,其余属性为{ id: string }类型的对象),提供两种可行方案:

方案1:宽松约束(允许其他属性为boolean或{ id: string })

直接扩展索引签名的类型范围,包含boolean和{ id: string },同时显式声明pending属性:

type CustomType = {
  pending: boolean;
  [key: string]: { id: string } | boolean;
};

const myObj: CustomType = { pending: true, key1: { id: 'val1' }, key2: { id: 'val2' } };

方案2:严格约束(仅pending为boolean,其余必须是{ id: string })

使用泛型结合交叉类型,确保除pending外的所有属性都符合{ id: string }类型,同时支持自动推断:

// 工具函数自动推断额外属性的键
const createCustomObj = <T extends Record<string, { id: string }>>(obj: { pending: boolean } & T) => obj;

// 直接使用,无需手动指定类型
const myObj = createCustomObj({ pending: true, key1: { id: 'val1' }, key2: { id: 'val2' } });

或者手动指定额外属性的键,实现更严格的类型检查:

type StrictCustomType<T extends string> = {
  pending: boolean;
} & { [K in T]: { id: string } };

const myObj: StrictCustomType<'key1' | 'key2'> = { pending: true, key1: { id: 'val1' }, key2: { id: 'val2' } };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:12:36