Description
Suggestion
π Search Terms
private set
shorthand accessor
β Suggestion
In C# you can do this:
public class User {
public string Name { get; private set; }
}
to reach this in TypeScript you have to write a short novel:
export class User {
private _name: string;
public get name(): string {
return this._name;
}
private set name(name: string) {
this._name = name;
}
}
This works great. But is a lot of code for such a tiny thing.
Write less code with less risk of errors. Otherwise you have to create a mirrored variable with e.g. leading _
underscore. And write this stupid short code. It's harder to read. You write the name and types over and over again. And possible make a mistake. But anyway, it would great to short up this by C# inspired syntax or a new keyword. Something between private
and public
. A keyword for private set; public get
.
But I'm not sure how TypeScript will handle this. I think code needs to be added to JavaScript during compilation. But how to avoid collisions? I mean just adding _{variableName}
is maybe not the best idea. It must be added to a hidden layer. ... Anyway, this is just a suggestion hoping you have a better idea than me.
The syntax can be similar to C# or a new keyword. It world be create to have a short way to make a property readonly for public and writeable in private scope. In best case with an initial value.
class User {
public get private set name = 'Foo';
}