-
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
[BUG]: Generic as interface key does not result in corresponding value #57372
Comments
This is working as intended. It's perfectly fine to call the generic function this way: const rec: Record<number, number[] > = { 0: [0, 1] };
doSomething<'a' | 'b'>('a', rec); |
Another "extends oneof" issue, see also #27808. You can use the distribution behavior as a workaround: const doSomething = <K extends keyof I>(...[key, value]: K extends unknown ? [key: K, value: I[K]] : never) => {
if (key === 'a') {
console.log(key); // key is the literal 'a' βοΈ
console.log(value);
// ^ Record<number, string[]> βοΈ
} else {
console.log(key); // key is the literal 'b' βοΈ
console.log(value);
// ^ Record<number, number[]> βοΈ
}
} |
You're indeed right. I did not think of this case.
Thanks for providing this example on how to fullfill my needs and also linking the "extends oneof" issue! π |
It's not just you; a lot of people don't think of this. The type-theoretical implications of untagged union and intersection types are... quite interesting, but most mainstream languages don't have such a concept so they're easy to overlook. A good way to think about union types, I've found, is to consider a |
In this example, how might i define the returned type as dependent on |
π Search Terms
generic, widen, interface
π Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about Generics and Interfaces
β― Playground Link
https://www.typescriptlang.org/play?ts=5.3.3#code/JYOwLgpgTgZghgYwgAgJLIN4Chm+XALmQCUIEB7KAEwB4QBXAWwCNoAaZAZzClAHMA2gF0AfAG4ceZkVIVqdJqygcGLaMPFYAvliwUQ3ZFXIBlcowhgAFv2QBeZDQDSyCAA9IIKp2QBrCACe5DBoIgAU-gFEThwAbnAANvQQRKgCTkIAlPYimJK4wCERgfZ2DgDkcOXZ2Hh1yPqc5AkQAHQJ5HzFAZliyAD0-X4lwD7WKAnAkFCJyJXlyIAo5IDwf-n1jc1tHV3xSRC9a-VHuIPIAHoXFyRklLSqShzcvCCCosgAPtdyd4rsyPfqUSHY71U7uAAOZEgVBkN3kAOUXB4-A0ay0rgSnBQtWOGxa7U63V6AyGkWQo2Q42Qk2ms3KzAWK2BuDxW0Ju2SBxB3NOlyusluCjUiKeKLenwF8N+iIRqO5ILBbkhCGhsO+Qoe-2lcrwOi0QA
π» Code
π Actual behavior
value
in line 9 (whenkey
is'a'
) is considered to be typeRecord<number, string[]> | Record<number, number[]>
.accordingly,
value
in line 14 (whenkey
is'b'
) is also considered to be typeRecord<number, string[]> | Record<number, number[]>
π Expected behavior
value
in line 9 (whenkey
is'a'
) should be considered to be typeRecord<number, string[]>
.accordingly,
value
in line 14 (whenkey
is'b'
) should be considered to be typeRecord<number, number[]>
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: