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

如何为未知结构的对象数组定义TypeScript类型?

问题解决:TypeScript未知结构对象的类型定义

你遇到的错误原因很明确:Record<string, string | number | boolean>等价于带有必填索引签名的类型,它要求对象必须支持用任意string类型的键访问并返回对应值。但User接口只有name一个明确属性,没有索引签名,TypeScript判定它无法满足“任意string键都能返回有效值”的要求,因此抛出类型不兼容的错误。

下面是三种针对性的解决方案:

方案一:给目标接口添加索引签名

如果允许你的User类型拥有其他符合值类型的属性,可以给它添加索引签名,让它兼容Row类型:

type Row = Record<string, string | number | boolean>;

interface User {
    name: string;
    // 新增索引签名,声明任意string键的值都符合类型要求
    [key: string]: string | number | boolean;
}

const objArr: User[] = [
    {name: 'John'},
    {name: 'Jack'}
];

const testArr: Row[] = objArr; // 类型兼容,无错误

方案二:修改Row为可选索引签名类型(推荐)

这种方式更贴合“未知结构对象”的需求:它允许对象拥有任意string键(也可以没有),只要存在的键对应的值是string/number/boolean即可,不需要强制支持所有string键的访问:

// 用可选索引签名定义Row
type Row = { [key: string]?: string | number | boolean };

interface User {
    name: string;
}

const objArr: User[] = [
    {name: 'John'},
    {name: 'Jack'}
];

const testArr: Row[] = objArr; // 类型兼容,无错误

方案三:使用类型断言强制转换

如果不想修改Row或User的类型结构,可以用类型断言告诉TypeScript强制转换类型(前提是你确定User的所有属性都符合Row的值约束):

type Row = Record<string, string | number | boolean>;

interface User {
    name: string;
}

const objArr: User[] = [
    {name: 'John'},
    {name: 'Jack'}
];

const testArr: Row[] = objArr as Row[]; // 类型断言实现转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:20:30