You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 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.
Suggestion
Would it be possible to capture type info on one variable inside the type of another one?
Most telling example:
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:
The text was updated successfully, but these errors were encountered: