-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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
Narrowing with in
keyword and const
identifier
#61463
Comments
Sounds like a duplicate of #55561 (comment). |
I don't see how this could really be made to work except through brute iteration, which would quickly become computationally infeasible in more complex situations. You have a |
Could you explain the brute iteration idea? I don't know anything about the implementation but perhaps its not necessarily a narrowing because there is no real type to reduce down to. But perhaps its more of a new feature tacked on to the typeof obj within the |
This issue has been marked as "Design Limitation" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
I understand a concern of computation if it basically does ...
export type Values = Obj_Values[keyof Obj_Values];
const obj: Obj;
const key: Obj_Key;
if (key in obj) {
console.log(obj[key] as Values) // Significantly more preferred
console.log((obj as Obj_Values)[key]) // Than this
} |
π Search Terms
"narrowing", "in", "const", "identifier"
β Viability Checklist
β Suggestion
Currently narrowing with the
in
keyword only works with a string literal in theif
or if the identifier's type is a string literal. However, aconst
identifier with the type of a union of string literals feels like it should work the same way.It can only ever be one of the literals and thus be a good candidate for narrowing.
For example:
This might be easier said than done as there doesn't exist a way to convey what the post narrow type would even look like. But it seems like a good thing to talk about.
π Motivating Example
Further improving narrowing in situations where runtime code is dynamic enough to not want to use string literals but the literals are known in the types.
π» Use Cases
Code that uses types generated off of schemas but the runtime code doesn't need to be coupled to schema changes by requiring updates where narrowing happens.
Lack of narrowing pushes you towards unsatisfactory workarounds.
Casting to types that are lies or any.
The text was updated successfully, but these errors were encountered: