Akumachan
Akumachan

Reputation: 129

Can you have option object arguments be as members in class constructor?

In Typescript, each constructor arguments with an accessor are recognized as class members.

class Test {
  constructor(private arg1, private arg2) { }
                      ~~~~          ~~~~ recognized as members
}

And you can use "options object".

class Test2 {
  constructor({arg1, arg2}: {arg1: string, arg2: number}) { }
}

or

class Test3 {
  constructor(options: {arg1: string, arg2: number}) { }
}

Then, are there any ways to define members based on each arguments in constructors with options object?

Like:

class Test4 {
  constructor({private arg1, private arg2}: {arg1: string, arg2: number}) { }
}

Do I have to define class members independently?

class Test4 {
  private arg1: string
  private arg2: number
  constructor({arg1, arg2}: {arg1: string, arg2: number}) {
    this.arg1 = arg1
    this.arg2 = arg2
  }
}

Upvotes: 0

Views: 291

Answers (1)

zS1L3NT
zS1L3NT

Reputation: 500

Stated below is the best you can do with TypeScript.

class Test1 {
    constructor(private arg1: string) {}
}

class Test2 {
    constructor(private options: { arg1: string; arg2: number }) {}
}

I think what you are trying to do is deconstruct options and set their properties in the class. You cannot deconstruct the properties of options directly in the parameters of the constructor. So this one line in the constructor might help

class Test2 {
    constructor(private options: { arg1: string; arg2: number }) {
        Object.assign(this, options)
    }
}

But the issue with this solution is that you don't get type annotations for this.arg1 and this.arg2 even though they exist in the class. So it's best if you stick to assigning each property separately

Upvotes: 1

Related Questions