多维数组的TypeScript类型定义

3
我正在创建一个布尔值的矩阵 / 2D 数组,并且希望推断一个不仅仅是“ANY”的类型,以用于数据网格(datagrid)。
let yearRange = [2000,2001,2002,2003,2004];
let monthRange = [0,1,2,3,4,5,6,7,8,9,10,11];
let dateGrid = any;

yearRange.forEach((year) => {
    monthRange.forEach((month) => {
        dateGrid[year][month] = true;
    });
});

如何为dategrid创建一个接口/类型,以便:

推断结构:例如dateGrid[yearIndex][possibleMonthValues]:boolean 并限制月份索引仅适用于适用的月份。

dateGrid[2000][0] = true
dateGrid[2000][1] = true
dateGrid[2000][2] = true
dateGrid[2000][3] = true
dateGrid[2000][4] = true
dateGrid[2000][5] = true
dateGrid[2000][6] = true
dateGrid[2000][7] = true
dateGrid[2000][8] = true
dateGrid[2000][9] = true
dateGrid[2000][10] = true
dateGrid[2000][11] = true
dateGrid[2001][0] = true

... and so on ...

1个回答

1

基于记录的解决方案

为了严格起见,我们可以使用 const 关键字从您提供的变量中推断出适当缩小的类型。由于我假设年份只是一个例子,因此最好只限制月份,并将年份保留为 number 类型:

// use const in order to get proper types
let yearRange = [2000,2001,2002,2003,2004];
let monthRange = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] as const;
type Month = typeof monthRange[number];

let dateGrid: Record <number,Record<Month, boolean>>;

Record<月份, 布尔值> 是一个不错的想法,如果我们限制月份从0到11。如果我们只允许一部分月份,则可以创建非排他性记录:

let dateGrid: Record<number, Partial<Record<Month, boolean>>> = {
  [2000]: {
    "0" : false 
  }
} // valid as not all fields needs to be provided
const a = dateGrid[2000][4] // boolean | undefined

// in contrary exclusive type
let dateGridExclusive: Record<number, Record<Month, boolean>> = {
  [2000]: {
    "0" : false 
  }
} // error all months need to be provided
const b = dateGrid[2000][4] // boolean

请注意,我使用了Partial实用程序类型,以放松约束并允许提供部分月份。

基于数组的解决方案

如果我们想将其作为数组使用,我们可以考虑另一种数组类型:

type Months = [
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
  boolean,
]

let dateGrid: Months[] // array of 12 element tuples

使用年份级别的数组的缺点是,当我们从2000年开始设置这样的数组时,会有1999个未定义的值。

很不错,干得好!而且你对年数的估计是正确的。现在我唯一能看到的问题是我不能再把dateGrid当作一个“数组”来处理。例如:(dateGrid.flat().indexOf(false) !== -1); - Paul Deschamps

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接