Reputation: 1394
So I want to have as much single point of control in my typescript classes, as well as intellisense (using vscode). I havent found a good way to do this, however.
What I want to do is make a class that 1. Has properties 2. Takes in properties via a constructor 3. Assigns the constructor values to the class properties
Sounds really easy. However, the solution has to be able to add new properties, or remove properties, by only changing a single line of code, and still have intellisense know what properties are in my class. Additionally, I don't want my object to merely hold another object with all my desired properties.
Examples. (warning, 4 space tab width and no semicolons)
class Entity {
name: string
val: number
constructor(name: string, val: number) {
this.name = name
this.val = val
}
}
In this example, if I want to add a new property, I'd have to add it in three new places. 1. The properties list 2. The constructor signature 3. Assigning inside the constructor So I don't have single point of control, moreso triple point of control
The benefits of this, however, is that theres full intellisense support, and all the properties are part of the class itself, not an object inside my class
Another example
interface IEntity {
name: string
val: number
}
class Entity {
data: IEntity
constructor(data: IEntity) {
this.data = data
}
}
Here, if I want to add or remove a property, I only have to do so in one place, in the interface. Awesome! Additionally, I get full intellisense support. However, if i wanna access any of my properties, I'd have to do class.data. , rather than class., which is an unnecessary abstraction. I could add getters and setters, but that would ruin the point of single point of control.
Last example
class Entity {
name: string
val: number
constructor(data: Entity) {
;(<any>Object).assign(this, data)
}
}
This, IMO, is the best example I can think of. 1. Single point of change (only have to change what my class properties are) 2. I don't have to access by using class.data., i can do class. (however, i do have to pass an object into the constructor, which some may argue is instrinsically better) 3. Full intellisense support
Anybody have better ideas, or a method similar to the third example that doesnt force me to pass in an object to the constructor?
Thanks!
Upvotes: 0
Views: 88
Reputation: 1991
There is a shortcut in TypeScript for class property assignment. You just need to put the access type keyword in parameter declaration in the constructor. For example, if you want your name
and val
to be public (which is the default), you simply have to do:
class Entity {
constructor(public name: string, public val: number) { }
}
And that's it! It will replace properties declaration, parameters, and assignments.
Upvotes: 3