我们知道在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);