Least redundant ts class declaration
Unanswered
Large oak-apple gall posted this in #help-forum
Large oak-apple gallOP
What is best way to declare classes without multiplicating same keywords multiple times each?
What I tried:
- basic declaration with type: each property is repeated 4 times
- skip type: need to duplicate type declarations in class properties and in constructor
- Object.assign: could be best, but breaks types in instances
- factory: could be second best, but not available for methods
Example code. It can potentially have many fields, so writing each more than once is biggest obstacle.
Perfect solution would be Object.assign, if it worked with types properly
What I tried:
- basic declaration with type: each property is repeated 4 times
- skip type: need to duplicate type declarations in class properties and in constructor
- Object.assign: could be best, but breaks types in instances
- factory: could be second best, but not available for methods
Example code. It can potentially have many fields, so writing each more than once is biggest obstacle.
Perfect solution would be Object.assign, if it worked with types properly
type EntityType = {
name?: string | null
}
class Entity implements EntityType {
name
constructor(input: EntityType) {
this.name = input.name
}
hello() {
console.log('hello', this.name)
}
}2 Replies
Pacific sand lance
why not inheritance?
class BaseEntity {
private name: string;
public constructor(name: string) {
this.name = name;
}
public hello(): void {
console.log("hello", this.name);
}
}
class Entity extends BaseEntity {
public constructor(name: string) {
super(name);
}
}
const entity = new Entity("...");
entity.hello();also to ensure
BaseEntity can't be instantiated you can make it abstract