microsoft / microsoft/TypeScript
Type inference only works on the same line as the variable declaration
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.3k
- 平均マージ
- 2日 4時間
- マージ済み PR(30日)
- 132
説明
I ran into this odd behavior while writing some tests, that do the typical describe, declare a closure-scope variable, and in beforeEach, assign some object to that variable that is used in each of the tests inside.
Search Terms:
infer, inference, closure, scope, broken, any, cast
Initially, I thought it was limited to closure scope, but I then started reducing the reproduction sample more and more, and realized, it's broken even if it's on the very next line:
Code
// given
interface Foo {
id: string;
}
function make(): Foo {
return {
id: 'akatechis',
}
}
// u1 is correctly inferred to be of type Foo.
let u1 = make();
// u2 is incorrectly inferred to be of type any.
let u2;
u2 = make();
// this was the scenario in which I originally ran into this:
// a closure scoped variable that is assigned in an inner function
function outer () {
// u3 is inferred to be of type any
let u3;
return {
inner() {
// u3 here is still any
u3 = make();
// surprisingly, returning u3 here causes the return type of inner() to be Foo, not any???
return u3;
}
}
}
Expected type declarations:
interface Foo {
id: string;
}
declare function make(): Foo;
declare let u1: Foo;
declare let u2: Foo; // <---- this should have been inferred to be Foo
declare function outer(): {
inner(): Foo;
};
Actual type declarations:
interface Foo {
id: string;
}
declare function make(): Foo;
declare let u1: Foo;
declare let u2: any;
declare function outer(): {
inner(): Foo;
};
Playground Link: playground
Related Issues:
The only thing that I found somewhat close to this issue was the question in the FAQ about unused generic types causing type widening, but I don't think this is it, because I'm not using generics here.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンクされている TypeScript Playground の再現コードから始め、u1、u2、outer() について推論された宣言を比較します。type widening に関する関連 FAQ エントリを読んでその説明を除外し、次に不一致の原因となっている型推論の挙動を特定します。u2 が Foo として推論され、示されている outer() の結果が維持されれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 35/100