Skip to content

Capture type info in a variable's type #52289

Closed

Description

Suggestion

Would it be possible to capture type info on one variable inside the type of another one?
Most telling example:

const useNumber = (n: number) => { ... };
const obj: { number?:  number } = getObj();
const hasObj = obj.number != null;
if (hasObj) {
  useNumber(obj.number); // error: number | undefined not assignable to number
}

I often write variables like hasNumber to make the code more explicit, and it would be nice if the semantic meaning of their names was reflected in the type system by capturing type info on other variables.

🔍 Search Terms

capture type information variable

✅ Viability Checklist

My suggestion meets these guidelines:

  • ❓ This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • ✅ This wouldn't change the runtime behavior of existing JavaScript code
  • ✅ This could be implemented without emitting different JS based on the types of the expressions
  • ✅ This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • ✅ This feature would agree with the rest of TypeScript's Design Goals.

Activity

  1. fatcerberus commented on Jan 18, 2023

    @fatcerberus

    This should already work but obj.number must be defined as readonly. See #44730.

    Narrowing through indirect references occurs only when the conditional expression or discriminant property access is declared in a const variable declaration with no type annotation, and the reference being narrowed is a const variable, a readonly property, or a parameter for which there are no assignments in the function body.

    #44730 (comment) for rationale

  2. Etchelon commented on Jan 18, 2023

    @Etchelon
    Author

    Great to know, thanks! I checked and it works, event more than 1 level deep apparently!

  3. locked as resolved and limited conversation to collaborators on Oct 22, 2025
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions