microsoft / microsoft/TypeScript
Allow declaring properties inside class constructors
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
It's a little clunky setting up properties in classes right now.
Here's what I have to do at the moment to set a property value in the constructor:
class Animal {
public interruptedSound: string;
constructor(public sound: string) {
this.interruptedSound = sound.substring(0, 3);
}
}
let dog = new Animal("woof");
console.log(dog.sound); // woof
console.log(dog.interruptedSound); // woo
Notice that interruptedSound's setup is split over two lines, and I have to declare it as a string even though it could be inferred from the fact that sound.substring returns a string.
What I'd like to be able to do:
class Animal {
constructor(public sound: string) {
this.interruptedSound = sound.substring(0, 3); // now a detectable property of type string
}
}
let dog = new Animal("woof");
console.log(dog.sound); // woof
console.log(dog.interruptedSound); // woo
This would avoid having to declare all properties at the top before being able to use them in constructors, saving a lot of boilerplate on complex classes. F# already does something similar to make setting up types much quicker and simpler. There wouldn't be any JavaScript compatibility issues, because JavaScript already works this way.
In cases where the property is declared separately, give precedence to the declaration.
The private, public or readonly keywords could even be used before the assignment to modify the property, e.g.
class Animal {
constructor(public sound: string) {
private readonly this.interruptedSound = sound.substring(0, 3);
}
changeSounds() {
this.sound = "meow";
this.interruptedSound = "meo"; // error, interruptedSound is readonly
}
}
let dog = new Animal("woof");
console.log(dog.sound); // woof
console.log(dog.interruptedSound); // error, interruptedSound is private
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No files, tests, or compiler entry points are named in the issue. Start by reviewing the proposed constructor-assignment examples and the existing handling of class properties and constructor parameter properties; done would mean supporting the requested syntax with inferred types and the stated declaration, visibility, and readonly behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100