Skip to content

Capture type info in a variable's type #52289

Closed
@Etchelon

Description

@Etchelon

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.

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