wgf4242
wgf4242

Reputation: 831

typescript destructuring assignment with interface

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'

Upvotes: 2

Views: 11323

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44087

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 };

Upvotes: 5

Related Questions