最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - typescript destructuring assignment with interface - Stack Overflow

programmeradmin2浏览0评论

I tried to destructuring assignment with interface, but cannot write like this.

interface TYPE {
  id?: number;
  type?: string;
}

const e =  {
  'id': 123,
  'type': 'type_x',
  'other': 'other_x'
}
const {...foo}: {foo: TYPE} = e;
console.log(foo.id, foo.type) // expected: 123, 'type_x'

I tried to destructuring assignment with interface, but cannot write like this.

interface TYPE {
  id?: number;
  type?: string;
}

const e =  {
  'id': 123,
  'type': 'type_x',
  'other': 'other_x'
}
const {...foo}: {foo: TYPE} = e;
console.log(foo.id, foo.type) // expected: 123, 'type_x'
Share Improve this question edited Aug 4, 2019 at 6:48 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked Aug 4, 2019 at 6:27 wgf4242wgf4242 8313 gold badges12 silver badges23 bronze badges 2
  • 3 What do you expect const {...foo}: {foo: TYPE} = e; to do exactly? – Alex Wayne Commented Aug 4, 2019 at 6:53
  • const {...foo, ...rest}: {foo: TYPE, rest: any} = e,; to desctruct assign TYPE, and rest propterties, but not write like this. – wgf4242 Commented Aug 4, 2019 at 13:20
Add a ment  | 

1 Answer 1

Reset to default 5

Just declare the type on the variable, without that weird object notation:

const { ...foo }: TYPE = e;

That is a weird way to make a copy of an object however - it's usually done like so:

const foo: TYPE = { ...e };
发布评论

评论列表(0)

  1. 暂无评论