0

I'm not sure if I can't find an answer to this because it is not possible, but I find myself wanting to instantiate a class with an object like so:

class Foo {    
  constructor(
    public id: number,
    public bar: string,
    public y: number,
    public z: string
  ) {}    
}

let x = new Foo({bar: 'testing', z: 'test'})

Instead, this will attempt to set id equal to {bar: 'testing', z: 'test'} which is not what I want. I'd like it to create an instance of Foo with Foo.bar = 'testing' and Foo.z = 'test'.

Is the only way to define the object like new Foo(null, 'testing', null, 'test')?

Jeremy Thomas
  • 6,240
  • 9
  • 47
  • 92
  • This looks like a candidate for ["object destructuring"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring) –  Mar 22 '18 at 14:53
  • Also look at this question for a more TS oriented solution : https://stackoverflow.com/questions/49061774/how-to-build-a-typescript-class-constructor-with-object-defining-class-fields/49062616#49062616 – Titian Cernicova-Dragomir Mar 22 '18 at 14:54

0 Answers0