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

如何为指定年月范围的布尔矩阵dateGrid定义TypeScript类型

为布尔矩阵dateGrid定义严格的TypeScript类型

没问题,咱们来一步步解决这个TypeScript类型定义的问题,让你的dateGrid拥有严格的类型约束,彻底告别any!

第一步:让TypeScript捕获具体的年份和月份数值

首先,我们需要把你的yearRange和monthRange转为只读元组,这样TypeScript就能推断出数组里的具体数值,而不是宽泛的number类型。只需要在数组后面加上as const:

const yearRange = [2000,2001,2002,2003,2004] as const;
const monthRange = [0,1,2,3,4,5,6,7,8,9,10,11] as const;

第二步:提取年份和月份的类型

基于上面的只读元组,我们可以用typeof和索引类型提取出具体的年份、月份类型:

type Year = typeof yearRange[number];
type Month = typeof monthRange[number];

现在Year的类型就是2000 | 2001 | 2002 | 2003 | 2004,Month的类型是0 | 1 | 2 | ... | 11,完全符合你的合法值要求。

第三步:定义DateGrid的类型

接下来我们定义DateGrid类型,它是一个嵌套的索引类型:外层键是Year类型,对应的值是一个对象,内层键是Month类型,值为boolean:

type DateGrid = {
  [Y in Year]: {
    [M in Month]: boolean;
  };
};

第四步:正确初始化并填充dateGrid

注意:原来的代码直接给dateGrid[year][month]赋值会报错,因为初始时dateGrid是空的,没有对应的年份对象。我们需要先初始化每个年份的结构,再填充月份值:

// 初始化dateGrid,先创建所有年份的空对象
const dateGrid: DateGrid = {
  2000: {},
  2001: {},
  2002: {},
  2003: {},
  2004: {}
} as DateGrid;

// 填充布尔值
yearRange.forEach((year) => {
  monthRange.forEach((month) => {
    dateGrid[year][month] = true;
  });
});

效果验证

现在你会得到完美的类型约束:

  • 只有yearRange里的年份能作为dateGrid的键,比如dateGrid[2005]会直接报错
  • 每个年份下的月份只能是0-11,比如dateGrid[2000][12]也会报错
  • 每个值必须是boolean类型,赋值非布尔值会提示错误
  • IDE还会自动补全合法的年份和月份哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:12:28