【问题标题】:How to initialize array to tuple type in TypeScript?如何在 TypeScript 中将数组初始化为元组类型?
【发布时间】:2019-10-19 12:28:45
【问题描述】:

我正在使用 React/Redux 制作数独网络应用程序。但是我在打字时遇到了一些问题。

当前代码:

// 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. 这种情况有好的解决办法吗?
  2. 如果为 1,解决方案是什么?

【问题讨论】:

    标签: javascript arrays typescript multidimensional-array typescript-typings


    【解决方案1】:

    对于9,我会做你所做的。

    否则你会遵循旧的函数式编程说法:If its pure on the outside, it doesn't matter if its impure on the inside,并战略性地使用Tuple9type 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));
    }
    

    【讨论】:

    • 谢谢 :) const getEmptyBoard: (() =&gt; Board) = () =&gt; new Array(9).fill(0).map(() =&gt; new Array(9).fill(0)) as Board; 此代码有效!
    【解决方案2】:

    类型在运行时不存在意味着没有办法说“给定类型 A 构建运行时数组 X”

    更程序化的构建方式类似于

    new Array(9).fill(0).map(() => new Array(9).fill(0))
    

    【讨论】:

    • 这是我的解决方案之一,但由于两者不兼容而不起作用。
    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 2021-12-02
    • 2022-08-19
    • 2020-08-20
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多