KnownKeys<T> breaking change in 4.3.1-rc
See original GitHub issueBug Report
🔎 Search Terms
KnownKeys, never, getting known interface keys
🕗 Version & Regression Information
- This changed between versions 4.3.0-beta and 4.3.1-rc
⏯ Playground Link
- 4.3.0-beta playground – types work.
- 4.4.0 playground – types fail. This issue also exists in 4.3.1-rc but that version isn’t in the playground.
💻 Code
type KnownKeys<T> = {
[K in keyof T]: string extends K ? never : number extends K ? never : K
} extends { [_ in keyof T]: infer U } ? U : never;
interface HasStringKeys {
[s: string]: any;
}
interface ThingWithKeys extends HasStringKeys {
foo: unknown;
bar: unknown;
}
const demo: KnownKeys<ThingWithKeys> = 'foo';
🙁 Actual behavior
demo
has type never
.
🙂 Expected behavior
demo
has type 'foo' | 'bar'
.
Other info
I’m not sure where I got KnownKeys
from, but it appears on https://stackoverflow.com/a/51956054/123395.
This issue impacted https://www.npmjs.com/package/idb, but I’ve already worked around the issue by using the other method on that StackOverflow post. https://github.com/jakearchibald/idb/commit/e3c76a59f6ab461b03ceabebc24dea826a074a76
Issue Analytics
- State:
- Created 2 years ago
- Reactions:7
- Comments:7 (3 by maintainers)
Top Results From Across the Web
No results found
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
For others that run into this issue, the workaround was to replace
KnownKeys
with:Edit: I switched to @DanielRosenwasser’s version in https://github.com/microsoft/TypeScript/issues/44143#issuecomment-843450189, since it’s compatible with more TS versions. The workaround above caused compat issues https://github.com/jakearchibald/idb/issues/223
The root cause is basically because
string extends keyof T
is true, so we fall into thenever
branch when calculating the implied constraint ofinfer U
. We need to fix up that logic to, rather than instantiate the template to remove theK
type parameter, resolve constraints in the template instead. A simplegetBaseConstraintOfType
instead of our complex instantiation logic may do nicely.