Skip to content

Capture type info in a variable's type #52289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Etchelon opened this issue Jan 18, 2023 · 2 comments
Closed

Capture type info in a variable's type #52289

Etchelon opened this issue Jan 18, 2023 · 2 comments

Comments

@Etchelon
Copy link

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.
@fatcerberus
Copy link

fatcerberus commented Jan 18, 2023

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

@Etchelon
Copy link
Author

Etchelon commented Jan 18, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants