microsoft / microsoft/TypeScript

Inference isn't working with constructor that contextually types 'this' with intersections of itself

オープン
#12,846 コメント 2 件 リアクション 2 件 担当者 0 名 GitHub で見る

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

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

説明

TL;DR: There should be no errors in the below example.

I am trying to model a library that takes an options bag for its constructor, and exposes those properties onto the instance that is eventually produced.

For example, if I wrote

let instance = new Component({
    methods: {
        hello() { }
        world() {
            this.hello();
        }
    }
});

I should be able to write instance.hello() or instance.world().

Additionally, since this in world will be bound to the instance, this.hello should be legal and well-typed in the above example.

However, I'm not able to come up with a version of this that works.

/**
 * Ensures all properties have a `this` param of type `T`.
 */
interface ThisEnforced<T> {
    [prop: string]: (this: T, ...args: any[]) => any;
}

interface ComponentOptions<Methods> {
    methods?: Methods
}

interface Component<Methods extends ThisEnforced<Component<Methods> & Methods>> {
    $methods: Methods;
}

interface ComponentStatic {
    new <Methods extends ThisEnforced<Component<Methods> & Methods>>(options: ComponentOptions<Methods>):
        // Returns...
        Component<Methods> & Methods;
}
declare var Component: ComponentStatic;

let inst = new Component({
    methods: {
        hello() {
            // ...
        },
        world() {
            this.hello;
            //   ~~~~~
            // Error: Property `hello` does not exist on this type.
        }
    },
});

inst.hello;
//   ~~~~~
// Error: Property `hello` does not exist on this type.

In the above example, there should be no errors - however, it appears that no inferences are being drawn as a type argument for Methods, and both this.hello and inst.hello are causing errors.

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

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

はじめの一歩

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

調査の方向性

まず、issue にあるコンテキスト型付けとコンストラクター推論の例を再現し、world 内の this 型と inst の推論された型に注目してください。関連する TypeScript の型チェックとジェネリック推論の経路を追跡してください。完了の条件は、例でエラーが発生せず、this.hello が受け入れられ、適切な型付けで inst.hello を利用できることです。

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

評価

技術スタック
typescript
領域
compilers
issue の種類
バグ
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

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

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