1

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?

2 Answers 2

1

Types don't exist at runtime meaning that there is no way to say "given type A build run-time Array X"

The more programmatic way to build it would be something like

new Array(9).fill(0).map(() => new Array(9).fill(0))
Sign up to request clarification or add additional context in comments.

1 Comment

It is one of my solution but doesnt work cuz incompatible type of two.
0

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));
}

1 Comment

Thx :) const getEmptyBoard: (() => Board) = () => new Array(9).fill(0).map(() => new Array(9).fill(0)) as Board; This code works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.