#How to get class interface in its constructor?

8 messages · Page 1 of 1 (latest)

daring moat
#

I need to do smth like:

class Foo {
  name?: string;
  weight?: number;

  constructor(data: InstanceType<typeof Foo>) {
    Object.assign(this, data);
  }
}

but get an error:

'data' is referenced directly or indirectly in its own type annotation.(2502)

So how can I do it?

thin ironBOT
#
onkeltem#0

Preview:```ts
class Foo {
name?: string
weight?: number

constructor(data: InstanceType<typeof Foo>) {
Object.assign(this, data)
}
}

const f1: Foo = new Foo({name: "Fooo"})

console.log(f1)```

daring moat
#

I need to initialize class like this

#

To set all the data at once. It's needed in the API transformer layer

#

Sure, I don't want to declare the interface separately because it's literally a double input

#

I can think of:

  constructor(data: unknown) {
    const dataTyped = data as InstanceType<typeof Foo>;
    Object.assign(this, dataTyped);
  }
thin ironBOT
#
sandiford#0

Preview:```ts
class Foo {
name?: string
weight?: number

constructor(data: Foo) {
Object.assign(this, data)
}
}

const f1: Foo = new Foo({name: "Fooo"})

console.log(f1)```

final oxide
#

👆🏻