我正在使用React / Redux制作数独Web应用程序。但是我在键入时遇到了一些问题。
当前代码:
// typedef
type Tuple9<T> = [T, T, T, T, T, T, T, T, T];
export type Board = Tuple9<Tuple9<number>>;
// code using board type, I want to fix getEmptyBoard() to more programmatic.
const getEmptyBoard: (() => Board) = () => {
return [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
];
};
我想将getEmptyBoard()
修改为更具编程性。
答案 0 :(得分:1)
类型在运行时不存在,这意味着无法说“给定类型A构建运行时数组X”
更编程的方式构建它就像
new Array(9).fill(0).map(() => new Array(9).fill(0))
答案 1 :(得分:1)
对于9
,我会做你所做的。
否则,您将遵循古老的函数式编程:If its pure on the outside, it doesn't matter if its impure on the inside
,并战略性地使用Tuple9
type assertion:
type Tuple9<T> = [T, T, T, T, T, T, T, T, T];
function make9<T>(what: T): Tuple9<T> {
return new Array(9).fill(what) as Tuple9<T>;
}
export type Board = Tuple9<Tuple9<number>>;
function makeBoard(): Board {
return make9(make9(0));
}