microsoft / microsoft/TypeScript

Narrowing via property check fails when adding parent type to declaration

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

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

Needs Investigation
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

TypeScript Version: 3.8.3

Search Terms:

  • property check refinement

Expected behavior: No error, type is narrowed to SubA.

Actual behavior: Type is narrowed to never and produces an error.

Related Issues:

Code

This code type checks:

interface Base {
  base: number;
}

interface SubA extends Base {
  a: string;
  other: boolean;
}
interface SubB extends Base {
  b: string;
}

function foo(x: SubA | SubB | null) {
  x = x || {base: 1, b: 'b'};
  if (x && 'a' in x && x.a == 'str') {
    x.other;  // ok
  }
}

A very tiny tweak (adding Base | to the parameter type) breaks things, though:

function foo(x: Base | SubA | SubB | null) {
  x = x || {base: 1, b: 'b'};
  if (x && 'a' in x && x.a == 'str') {  // <-- Property 'a' does not exist on type 'never'. (2339)
    x.other;  // <-- Property 'other' does not exist on type 'never'. (2339)
  }
}

This makes some sense since foo could be called with something assignable to Base that has an a but is not specifically a SubA. But what doesn't make sense to me is that removing the assignment on the first line makes the error go away:

function foo(x: Base | SubA | SubB | null) {
  if (x && 'a' in x && x.a == 'str') {  // ok
    x.other;  // ok
  }
}

That assignment seeming has no bearing on if statement (the default value doesn't have an a property). So why does it affect the inferred type in it?

Either the second and third example should both error or neither of them should.

Output
"use strict";
function foo(x) {
    x = x || {base: 1, b: 'b'};
    if (x && 'a' in x && x.a == 'str') {
        x.other;
    }
}

Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

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

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

はじめの一歩

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

調査の方向性

提供されている TypeScript Playground の再現コードから始め、3 つの foo の例を比較してください。代入によってプロパティチェックによる narrowing がどのように変化するかに注目してください。これらの例全体で動作が一貫し、報告された never エラーが解消されるか、意図的に文書化されれば、issue は完了です。

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

評価

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

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

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