打字稿:如何在对象解构中定义rest属性的类型?

时间:2019-03-06 07:40:28

标签: javascript typescript destructuring definitelytyped

我们知道在Javascript中,我们可以使用Rest in Object Destructuring

const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10 
b; // 20 
rest; // { c: 30, d: 40 }

但是在Typescript中,我们如何定义rest属性的类型(接口)?

const {m, ...n}: {
  m: number;
  // TODO: how to define type n?
} = {
  m: 1,
  n0: '0',
  n1: '1',
  // ... n0~n10000 are all strings
  n9999: '9999',
  n10000: '10000',
};

这篇文章解决了这个问题:

@请参阅Destructuring a function parameter object and ...rest

所以最终的解决方案是:

const {m, ...n}: {
  m: number;
  // TODO: how to define type n?
  [k: string]: number | string,
} = {
  m: 1,
  n0: '0',
  n1: '1',
  // ... n0~n10000 are all strings
  n9999: '9999',
  n10000: '10000',
};
console.log(n.n0);

0 个答案:

没有答案