microsoft / microsoft/TypeScript
Contextual type doesn't apply to elements of array literal spread into another array literal
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
Bug Report
🔎 Search Terms
spread operator, type inference
🕗 Version & Regression Information
- This is the behavior in every version I tried
⏯ Playground Link
Playground link with relevant code
💻 Code
interface Test {
field: 'a' | 'b' | 'c'
}
let arr: Test[] = [
{ field: 'c' },
...[
{ field: 'a' }, // field: string
// ^?
{ field: 'b' }, // field: string
// ^?
]
]
function test(...args: Test[]): void {}
test(
{ field: 'c' },
...[
{ field: 'a' }, // field: string
// ^?
{ field: 'b' }, // field: string
// ^?
]
)
🙁 Actual behavior
The types of objects in the array nested through the spread operator is not inferred to be Test, as such inference begins from scratch, so the type of field in those objects becomes string (and is not detected to be 'a' | 'b' | 'c' which I specified in the interface), and a rather cryptic type error is shown:
Type '{ field: string; }' is not assignable to type 'Test'.
Types of property 'field' are incompatible.
Type 'string' is not assignable to type '"a" | "b" | "c"'.
I have also included an example with using the spread operator in a function call for completeness, it generates basically the same error.
I'm not sure if this is really a bug, but regardless, it is trivial to work around by just forcing compiler's hand a little by doing this:
let arr: Test[] = [
{ field: 'c' },
...[
{ field: 'a' as const },
{ field: 'b' as const },
]
]
Which forces the inferred types of the objects to actually be compatible, or assigning the spread array to a variable with an explicitly defined type:
let nested: Test[] = [
{ field: 'a' },
{ field: 'b' },
]
let arr: Test[] = [
{ field: 'c' },
...nested
]
🙂 Expected behavior
I would expect the type of expr3 in [expr1, expr2, ...expr3] to be inferred to be Iterable<T> or something like that provided that we know that the type of elements of the overall array is T. I believe that in my repro it would make types of nested objects to be inferred correctly as Test.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンクされた Playground の repro から始め、spread を含む配列リテラルのコンテキスト型付けの挙動を確認してから、関数呼び出しのケースについて Workbench の repro と比較します。ネストされたオブジェクト要素が、示されている as const や個別に型付けした配列による workaround なしで Test と互換性があるものとして推論され、両方の例が期待どおりに動作すれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 25/100