-
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
generic bound doesn't work when used in index type with concrete index type #51394
Comments
This is similar to #30581 and as such the current non-type-assertion solution is to refactor as mentioned in #47109, but the cure might be worse than the disease. So, TS is protecting you from doing this (unlikely in practice) terrible thing: const setValue = <K extends keyof Foo>(key: K, value: Foo[K][number]) => {
foo[key] = [value] // compiler error
}
setValue(Math.random() < 0.999 ? "a" : "b", "oopsie"); // no compiler error
foo.a.map(x => x.toFixed()) // 99.9% chance of runtime error Of course that same problem can happen in the version that "works": const setValue = <K extends keyof Foo>(key: K, value: Foo[K]) => {
foo[key] = value // no compiler error
}
setValue(Math.random() < 0.999 ? "a" : "b", ["oopsie"]); // no compiler error
foo.a.map(x => x.toFixed(2)) // 99.9% chance of runtime error But, as described in #30769 (comment)
The version that works has identical type _Foo<K extends keyof Foo = keyof Foo> = { [P in K]: Foo[P][number][] };
const _foo: _Foo = foo; // no compiler error
const setValue = <K extends keyof Foo>(key: K, value: Foo[K][number]) => {
const __foo: _Foo<K> = _foo; // no compiler error
__foo[key] = [value]; // no compiler error
} But, uh, all that to work around stuff so that it permits unsoundness without type assertions is a little much; you might as well just assert and move on: const setValue = <K extends keyof Foo>(key: K, value: Foo[K][number]) => {
foo[key] = [value] as Foo[K]; // no compiler error
} It would be nice if there were something better here, but I don't know what that would be. |
#30769 is related, as it's the source of the intersection behavior you see (
I'm not convinced it's that unlikely either. While nobody is going to write |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
π Search Terms
index type generic
π Version & Regression Information
4.9.0-dev.20221025
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
π Expected behavior
no error, since it works when the type of value is
Foo[T]
:The text was updated successfully, but these errors were encountered: