Issue
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?
Solution
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
Answered By - Tobias S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.