microsoft / microsoft/TypeScript

New Feature Requesting for `const` Parameter

オープン
#18,497 コメント 41 件 リアクション 172 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Awaiting More Feedback Suggestion
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
132

説明

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();

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、issue にある TypeScript の例を再現し、パラメーター宣言と control-flow narrowing が再代入をどのように扱うかを確認します。const パラメーターで受け入れられるセマンティクスと構文を定義し、そのうえで callback の例が type-check を通過し、再代入が拒否されることを検証します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
typescript
領域
compilers
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。