I guess, this is somewhat basic question, but I'm failing to google this (not sure about the correct keywords), so let me ask.
Imagine a simple class with a basic constructor:
class Animal {
name: string
constructor(name: string) {
this.name = name
}
}
The problem about this is somewhat obvious: with a growing number of properties (age: number; type: AnimalType
etc) one has to write those things thrice:
class Animal {
name: string
age: number
type: AnimalType
// ...
constructor(name: string, age: number, type: AnimalType) {
this.name = name
this.age = age
this.type = type
// ...
}
}
so the constructor
will get bigger and bigger, and the code is not particularly DRY. Is there some standart way to avoid this in TS? I can imagine something like
class Animal {
@Required name: string
@Required age: number
@Required type: AnimalType
// ...
constructor(anotherParam) {
// implicitly: this.name = name
// implicitly: this.age = age
// implicitly: this.type = type
// deal with anotherParam
}
}
but the syntax is not accurate, rather to illustrate the expected result.
The only simple solution that I'm aware of is to create an interface like this:
interface AnimalPermanentParams {
name: string
age: number
type: AnimalType
}
class Animal {
permanentParams: AnimalPermanentParams
// ...
constructor(permanentParams: AnimalPermanentParams, anotherParam) {
this.permanentParams = permanentParams
// ...
}
}
but this has an obvious drawback of an extra layer: we have to use this.permanentParams.age
instead of just this.age
. So are there any sane alternatives, ideally without 3d party libs?
CodePudding user response:
You can just declare the parameter as public
(or private
) and it will set the property for you.
class Animal {
constructor(public name: string) {}
}
new Animal("abc").name