microsoft / microsoft/TypeScript
New Feature Requesting for `const` Parameter
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
I have a small new feature to request. Let say we have this piece of code:
function setButton(button: Button | undefined) {
if (button) {
button.onclick = () => {
// tsc complains button might be undefined(well done!),
// because it might be set to undefined later on,
// as you can see below `button = undefined;`.
button.setAttribute('disabled', 'true'); //error
}
}
// some other code goes here...
// and eventually, button is set to undefined.
button = undefined;
}
Fortunately, there is a way to fix this:
function setButton(button: Button | undefined) {
const constButton = button;
if (constButton) {
constButton.onclick = () => {
// now tsc is satisfied.
constButton.setAttribute('disabled', 'true');
}
}
// impossible to assign to a const variable.
// constButton = undefined;
}
But can we twist the code a little bit, which is what I asking for? Something like this:
function setButton(const button: Button | undefined) {
if (button) {
button.onclick = () => {
button.setAttribute('disabled', 'true');
}
}
}
So you can see there really are some cases a const parameter might come to handy. Thank you.
P.S. Just for demonstrating the point, here's a full demo:
class Button {
onclick?: () => void;
performClick() {
if (this.onclick) this.onclick();
}
setAttribute(key: string, value: string) {
//set attribute to this button
}
}
function setButton(button: Button | undefined) {
if (button) {
button.onclick = () => {
button.setAttribute('disabled', 'true');
}
}
button = undefined;
}
const button = new Button();
setButton(button);
button.performClick();
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
Start by reproducing the TypeScript examples in the issue and reviewing how parameter declarations and control-flow narrowing handle reassignment. Define the accepted semantics and syntax for a const parameter, then verify that the callback example type-checks while reassignment is rejected.
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
- 25/100