【问题标题】:Types when destructuring arrays解构数组时的类型
【发布时间】:2015-11-02 14:44:37
【问题描述】:
function f([a,b,c]) {
  // this works but a,b and c are any
}

这样写可以吗?

function f([a: number,b: number,c: number]) {
  // being a, b and c typed as number 
}

【问题讨论】:

  • 我需要不同的数据类型

标签: arrays types typescript destructuring


【解决方案1】:

这是在参数列表中解构数组的正确语法:

function f([a,b,c]: [number, number, number]) {

}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
  • 如果所有参数都是同一类型,你能缩短这个语法吗? f([a, b, c]: [number]) {...}
  • @filipbarak f([a, b, c]: number[])
【解决方案2】:

是的,是的。在 TypeScript 中,您可以通过一种简单的方式来处理数组类型,即创建元组。

type StringKeyValuePair = [string, string];

你可以通过命名数组来做你想做的事情:

function f(xs: [number, number, number]) {}

但你不会命名内部参数。 另一种可能性是成对使用解构:

function f([a,b,c]: [number, number, number]) {}

【讨论】:

    【解决方案3】:

    使用 TypeScript 4.0,元组类型现在可以提供标签

    type Range = [start: number, end: number]
    

    【讨论】:

      【解决方案4】:

      我的代码如下所示

      type Node = { 
          start: string;
          end: string;
          level: number;
      };
      
      const getNodesAndCounts = () => { 
          const nodes : Node[]; 
          const counts: number[];
          // ... code here
      
      return [nodes, counts];
      }
      
      const [nodes, counts] = getNodesAndCounts(); // problematic line needed type
      

      typescript 在 TS2349 下方的行中给了我错误:无法调用类型缺少调用签名的表达式;

      nodes.map(x => { 
      //some mapping; 
          return x;
      );
      

      改行到下面解决了我的问题;

      const [nodes, counts] = <Node[], number[]>getNodesAndCounts();
      

      【讨论】:

        【解决方案5】:

        作为一个简单的答案,我想补充一点,您可以这样做:

        function f([a,b,c]: number[]) {}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-18
          • 2019-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-25
          相关资源
          最近更新 更多