Skip to content

Control flow analysis for dependent parameters only works when checking against literalsΒ #55766

Open

Description

πŸ”Ž Search Terms

narrow, parameters, typeof

πŸ•— Version & Regression Information

It never worked for typeof / asserts checks since the feature introduction in #47190; it's been mentioned here:

#47190 (comment)

⏯ Playground Link

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZmAMgSygUwE4EMA2AuGACgDpSsMBzCAgbQAMs6AaGMAVwFsAjTAXRgA+Mel2YxoGZGAq8AlDAC8APhgA3EMgAmiolhZd5ymAG8AUDBjI4uxQoUwARFgfyzFi6EggcaYjhAUhAYA3ObuAPTh7tHuAHoA-GEAvqYppp7Q8GAAghAQmFAEJGSU1MIMYuzcfILloiwSUjKGKupaOoR6MAaKKm6W1oTIENmdsq5hHuAQ3r7+gSGTMJExMQnJqenTsAgAKgCeAA5oIHBFpMTkVLRVPBgstzVCNI3SDVCS0nK9ahra9p19C0TGErEQoEcTtYsLZ7A5HhgXCDohlZn4AkFZKFoitVnFEhYUmk4GwwMAoMhwJYRoRVLgCKSANZgEAAdzAsgIdJw1JgFWRMAwaCgbAwYBgHzYaFCKSAA

πŸ’» Code

const fnLiteral: (...args: [`a`, number] | [`b`, string]) => void = (a, b) => {
  if (a === "a") {
    console.log(b);
    //          ^? number
  }
}

const fnAssert: (...args: [`a`, number] | [`b`, string]) => void = (a, b) => {
  if (isA(a)) {
    console.log(b);
    //          ^? number | string
  }
}
const fnTypeof: (...args: [number, number] | [string, string]) => void = (a, b) => {
  if (typeof a === "number") {
    console.log(b);
    //          ^? number | string
  }
}

function isA(val: unknown): val is `a` {
  return true;
}

πŸ™ Actual behavior

Both fnAssert and fnTypeof are unable to get TS to recognize b as its narrowed type (number). Only if a is checked against a literal does the narrowing works.

πŸ™‚ Expected behavior

The b parameter should be narrowed to number.

Additional information about the issue

No response

Activity

  1. Andarist commented on Sep 18, 2023

    @Andarist
    Contributor

    Currently only discriminated unions are supported and it only works if you check against the discriminant. This isn't unique to dependent parameters - it works exactly in the same way with object types: TS playground

  2. danvk commented on Jan 24, 2024

    @danvk
    Contributor

    Dupe of #32399?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Domain: check: Control FlowThe issue relates to control flow analysisHelp WantedYou can do thisPossible ImprovementThe current behavior isn't wrong, but it's possible to see that it might be better in some cases

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions