代码之家  ›  专栏  ›  技术社区  ›  cubefox

typescript中数组上的自定义键

  •  0
  • cubefox  · 技术社区  · 5 年前

    我有一系列数字,比如

    const arr:number[] = [0,12,14,18,24,36]
    

    我想将自定义密钥分配给

    arr.foo = 126
    

    但是,当我做这个时,脚本告诉我 Property 'foo' does not exist on type 'number[]'

    如何键入数组才能使此工作?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Muhammed Albarmavi    5 年前

    你可以创建一个接口来解决这个问题

    interface MyType<T> extends Array<T> {
        foo ?:number
    }
    
    const arr:MyType<number>= [0,12,14,18,24,36];
    
    arr.foo = 12