-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Type parameter cannot refine the other related type parameters #29276
Comments
In general, narrowing a value of a generic type does not give enough proof to narrow the type itself. For example: I could call the function like so: changeCount<"text" | "count">("text", 1); Observing that state[name] = value // error The type of The second error is raised also because, in general, type parameters cannot be narrowed. The type In this instance your type annotation is actually weakening the term, and removing the annotation removes the error. (Effectively you are going from if (isEqual("text" as "text", name)) {
const typeT = "";
state[name] = typeT; // ok
} I will cynically take this opportunity to plug my suggestion of uniform types #28430. In most cases the caller would never want to instantiate the call with a union type and so |
Generally we don't let the narrowing of one type parameter via control flow affect another, either. |
However this is a very common pattern in javascript, a function accept a key and corresponds value, and operate on object base on the key. |
This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow. |
TypeScript Version: 3.2.2
Search Terms: type prarameter refine
Code
Expected behavior:
Calling the function automatically refine other parameter
T
itself refined to'text'
The refinement also applied on the type parameter rely on
T
U
is nowextends string
value
is assignable tostate[name]
Actual behavior:
⭕ Calling the function automatically refine other parameter
❌
T
itself does not got refined to'text'
, onlytypeof name
does❌ The refinement does not applied on the type parameter rely on
T
becauseT
does not change❌
U
is still'extends Readonly<{ text: string; count1: number; count2: number; }>[T]'
❌
value
is not assignable tostate[name]
Playground Link:
link
Related Issues:
#4742 (not sure if it describes the exact same issue)
Notes
Although refinement on calling is useful enough in most case.
You still can't consume the type correctly in function body itself, which is quite annoying.
The text was updated successfully, but these errors were encountered: