我正在使用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()
修复为更具编程性。对于这种情况是否有好的解决方案?
如果为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));
}
关于javascript - 如何在TypeScript中将数组初始化为元组类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56436023/