typescript 如何为嵌套有其他数组的数组编写类型?

33qvvth1  于 2022-12-24  发布在  TypeScript
关注(0)|答案(1)|浏览(149)

我有以下结构:

[
    [
        [0,0,0],
        [1,1,1],
        [0,0,0],
    ],
        [
        [0,1,0],
        [0,1,0],
        [0,1,0],
    ]
]

我怎样才能避免这种丑陋的符号?也许通过写类型...

allPatterns: number[][][] = [];
qni6mghb

qni6mghb1#

为了清楚起见,您可以将内部类型标记为:

// Any set of three numbers
type MatrixRow = [number, number, number];
// Any set of three rows
type Matrix = [MatrixRow, MatrixRow, MatrixRow];

const exampleA: Matrix[] = [
    [
        [0,0,0],
        [1,1,1],
        [0,0,0],
    ], [
        [0,1,0],
        [0,1,0],
        [0,1,0],
    ]
];

const exampleB: Matrix[] = [];

您还可以为外部数组创建一个类型:

// A list of matrices
type MatrixSet = Matrix[];

const exampleC: MatrixSet = [];

TypeScriptPlayground

相关问题