我正在创建布尔的矩阵/ 2d数组,并且我想推断一个对dategrid而言不只是“ ANY”的类型。
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]:布尔值 并将月份指数限制为仅适用的月份。
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
...等等...
答案 0 :(得分: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>>;
如果我们将所有月份都限制为0到11, Record<Month, boolean>
将是一个好主意。如果一年中只允许部分月份,我们可以创建非排他记录:
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个未定义的值。