【问题标题】:How to write interface for a nested list?如何为嵌套列表编写接口?
【发布时间】:2019-04-13 10:56:45
【问题描述】:

我正在尝试在 Typescript 中为矩阵编写接口, 我找不到将Array<Array<number>> 类型描述为接口的方法。

    const matrix:Array<Array<number>> = [
        [0,0,0],
        [1,1,1],
        [0,1,0],
    ]

相反,我想要类似的东西

//dosen't work
    interface Imatrix {
    [index:number]:Array<number>
     }

然后可以在与 Imatrix 一起使用的函数中使用

function draw(matrix:Imatrix){
     matrix.forEach(()=>{
     //some code
      })
 }
draw(matrix)

当我这样做时,我得到错误 Property 'forEach' does not exist on type 'Imatrix'.ts(2339)

【问题讨论】:

    标签: typescript types interface


    【解决方案1】:

    如果你真的想使用一个接口,你可以这样做:

    interface Row<T> extends T[]
    {
      [cell: number]: T
    }
    
    interface Matrix<T> extends Row<T>[]
    {
      [cell: number]: Row<T>
    }
    

    (也许你想知道T[]Array&lt;T&gt; 的同义词。)

    但是 TypeScript 使用结构匹配,所以 typeinterface 没有区别,它们只是同一事物的不同语法。例如,这就是为什么我们不在接口名称前使用I 前缀的原因。我上面写的代码和这个是一样的:

    type Row<T> = T[];
    type Matrix<T> = Array<T[]>;
    

    如果您想将自己的方法添加到Matrix,正确的 OOP 方法是为其创建一个包含嵌套数组作为属性的类:

    type Row = number[];
    
    class Matrix
    {
      elements: Array<Row>;
    
      multiply(B: Matrix)
      {
        /* do something with elements */
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2020-01-05
      • 1970-01-01
      • 2021-09-08
      • 2023-03-06
      • 2023-04-10
      相关资源
      最近更新 更多