-
Notifications
You must be signed in to change notification settings - Fork 0
Description
JavaScript and Typescript traditionally use constructors like this
class Car {
make: string;
constructor(make: string) {
this.make = make;
}
}
class Toyota extends Car {
model: string;
constructor(make: string, model: string) {
super(make);
this.model = model;
}
}I have problems with this:
- Quite ugly and verbose
- It's quite hacky on the type system
- There's a default constructor, and you can even elide setting fields by setting them to readonly?? It isn't intuitive at all
I would prefer something that allowed us to create structs or classes that simply defined the data required, and allow you to create them. Any abstractions over that would be opt-in as generic static methods.
This was going to exist in E2 in the form of structs, I already implemented it. This was the syntax:
struct car {
make: string;
}
const Toyota = car { make = "test" }This could be abstracted away by having some constructor static function ala Rust, if you'd like.
function car:new(Make:string) {
return car { make = Make }
}No constructor or anything special needed. This works great because you clearly see which fields are needed, and for simple POD types you don't need to write a whole constructor.
Other languages than Rust do this, C# has object initialization syntax, and C++ has it too. Of course this is the same as a C struct, although I wanted to mention the other object oriented languages first.