javascriptarraystypescriptmultidimensional-arraytypescript-typings

How to initialize array to tuple type in TypeScript?


I'm making sudoku web app with React/Redux. But I have encountered some problem with typings.

Current code:

// 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]
  ];
};

I want to fix getEmptyBoard() to more programmatic.

  1. Is there good solution for this situation?
  2. If 1, What is solution?

Solution

  • For 9 I would do what you have done.

    Otherwise you would follow the old functional programming saying : If its pure on the outside, it doesn't matter if its impure on the inside and make a strategic use of 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));
    }