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
{{ message }}
Repository navigation
regression in 3.1+: mapped type cannot be used to index type #27413
// Given:// T = {foo: number}// The return type of T.select({bar: 'foo'}) should be// {bar: number}interfaceTable<T>{select<Uextends{[K: string]: keyofT}>(fields: U): {[KinkeyofU]: T[U[K]]}}
Expected behavior:
U[K] is keyof T and so T[U[K]] is computed successfully
Actual behavior:
Gives the error "Type 'U[K]' cannot be used to index type 'T'".
The same code compiles with tsc 3.0.3 and the return type gets computed correctly.
interfaceTable<T>{select<Uextends{[K: string]: keyofT}>(fields: U): {[KinkeyofU]: T[U[K]]}}declarevart: Table<{x: string}>;declareconsts: unique symbol;// your definition of `U` allows symbolic keys of `U` to have non-`keyof T` types,// which in turn means a call like this would typecheck. `T` indexed by one of these// types wouldn't exist, which is why we issue this errorconstresult=t.select({[s]: "not a key",member: "x"});// `result` above will end up of type `{[s]: unknown, member: string}`, since your type doesn't// actually handle the `symbol` key case
I assume, anyway. I actually tried what I think would be the correct version that fixes that, though:
(I left in the Extract so symbols on the input type get ignored, and the & keyof T in the index is what makes it typecheck despite the issue. It actually should have absolutely no effect on the resulting types when the generics are instantiated; but it shouldn't be necessary since the constraint of U[K] when K extends Extract<keyof U, string> aught to be keyof T as you implied.)
Activity
weswigham commentedon Sep 28, 2018
I assume, anyway. I actually tried what I think would be the correct version that fixes that, though:
and had the same issue; so something else must be the issue.
In any case, you can work around the problem by writing your type like so:
(I left in the
Extractso symbols on the input type get ignored, and the& keyof Tin the index is what makes it typecheck despite the issue. It actually should have absolutely no effect on the resulting types when the generics are instantiated; but it shouldn't be necessary since the constraint ofU[K]whenK extends Extract<keyof U, string>aught to bekeyof Tas you implied.)yseymour commentedon Sep 28, 2018
Thanks, good call on the workaround. U[K] used to be implicitly constrained to keyof T. I'm not sure exactly when the behaviour changed.
doing workaround based of microsoft/TypeScript#27413
fabb commentedon Jan 1, 2020
Maybe related:
This shows the error:
Type 'K[P]' cannot be used to index type 'T'.yseymour commentedon Jun 6, 2020
Closing this since it looks like the original issue is fixed.