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

如何为这类嵌套对象编写TypeScript类型定义?

为嵌套结构对象编写TypeScript类型定义的最优方案

问题背景

现有如下嵌套结构的JavaScript对象:

const dateButtons = {
  1: {
    id: 1,
    title: 'All',
    sortBy: { date: 'DD MMM YYYY', time: true },
  },
  2: {
    id: 2,
    title: '11 10 2022',
    sortBy: { date: 'DD MM YYYY' },
  },
  3: {
    id: 3,
    title: '20:11 11.10.2022',
    sortBy: { date: 'DD.MM.YYYY', time: true },
  },
  4: {
    id: 4,
    title: '11-10-2022',
    sortBy: { date: 'DD-MM-YYYY' },
  },
  5: {
    id: 5,
    title: '11 oct Thu',
    sortBy: { date: 'Do MMM dddd' },
  },
};

如果是数组形式,我会这样编写类型:

type myButtons = {
  id: number;
  title: string;
  sortBy: { date: string; time?: boolean };
}[];

但针对上述键为数字字符串、值为统一结构对象的嵌套结构,希望找到最优的类型定义方案,而非单独注册每个对象的类型。

解决方案

方案1:自定义类型+索引签名

先定义单个按钮的类型,再通过索引签名描述外层对象的结构:

// 定义单个按钮的核心类型
type DateButton = {
  id: number;
  title: string;
  sortBy: {
    date: string;
    time?: boolean; // 可选属性,适配部分对象没有time字段的情况
  };
};

// 外层对象类型:键为数字字符串,值为DateButton
type DateButtons = {
  [key: string]: DateButton;
};

// 给变量指定类型
const dateButtons: DateButtons = {
  // ... 你的对象内容
};

如果希望外层键严格限制为数字类型,也可以改用数字索引签名:

type DateButtons = {
  [key: number]: DateButton;
};

方案2:用typeof自动推导类型

如果对象已有具体初始值,完全可以让TypeScript自动推导精确类型,无需手动编写:

// 用as const让TypeScript推导最精准的类型(包括date字段的具体字符串字面量)
const dateButtons = {
  1: {
    id: 1,
    title: 'All',
    sortBy: { date: 'DD MMM YYYY', time: true },
  },
  2: {
    id: 2,
    title: '11 10 2022',
    sortBy: { date: 'DD MM YYYY' },
  },
  // ... 其余对象内容
} as const;

// 提取单个按钮的类型
type DateButton = typeof dateButtons[keyof typeof dateButtons];

// 提取外层对象的完整类型
type DateButtons = typeof dateButtons;

这种方案的优势是类型完全匹配现有对象结构,甚至能保留date字段的具体格式字面量,适合不需要扩展、只需匹配现有结构的场景。

方案3:用Record工具类型简化代码

TypeScript内置的Record工具类型可以快速定义键值结构的对象类型,写法更简洁:

type DateButton = {
  id: number;
  title: string;
  sortBy: { date: string; time?: boolean };
};

// Record<键类型, 值类型> 本质是索引签名的语法糖
type DateButtons = Record<string | number, DateButton>;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:45:23