-
Notifications
You must be signed in to change notification settings - Fork 12.8k
{ [K in keyof T]: T[K] } like type not work with generic type #33529
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
Comments
This would be unsound if you instantiated function test<T extends { a: string, b: string }>(obj: T) {
const test: Partial<T> = { a: 'a', b: 'b' };
return test.a
}
const result: 'b' | undefined = test({ a: 'b', b: 'a'} as const); // actually 'a' |
@jack-williams what are you mean? function test<T extends { a: string, b: string }>(obj: T) {
const test: Partial<T> = { a: 'a', b: 'b' } as T; // force no error.
return test.a
}
const result: 'b' | undefined = test({ a: 'b', b: 'a'} as const); // TS2322: Type '"a" | undefined' is not assignable to type '"b" | undefined'. Type '"a"' is not assignable to type '"b | undefined"'. |
Can you create a playground link that shows that error? |
@vipcxj What @jack-williams is trying to say is that the assignment doesn't work because the generic |
type Mix<B, T extends B> = { [K in keyof T]: K extends keyof B ? B[K] : T[K] }
type PMix<B, T extends B> = { [K in keyof T]?: K extends keyof B ? B[K] : T[K] }
type Base = { a: string, b: string }
interface EX extends Base {
a: '1';
}
const e: Mix<Base, EX> = { a: '3', b: '' }
function test<T extends Base>(obj: T): string | undefined {
const test: PMix<Base, T> = { a: 'a', b: 'b' }; // still not work here.
return test.a
}
let result = test({ a: 'b', b: 'a'} as const); // result is string | undefined now.
result = '3' |
@vipcxj It won't work, the assignment doesn't work for the same reason I mentioned above. Here is your modified example... |
@Siegrift |
Sorry, you're right. I don't know what is wrong with that code. I created even smaller example, but I don't get why it doesn't typecheck... (@jack-williams do you know why?) |
@Siegrift Your example doesn't work because you are still assigning a concrete value to something that is inherently generic. The error is correct here for the same reasons: const a: "b" | undefined = partial({ a: 'b' as 'b'}).a // no error, 'a' at runtime @vipcxj Returning a value of type |
@jack-williams Thank you very much. I wasn't able to create a counterexample. |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
@jack-williams please give me a example of |
TypeScript Version: 3.4.0-dev.201xxxxx
Search Terms:
Code
Expected behavior:
no error
Actual behavior:
TS2322 error
Playground Link:
Related Issues:
#33524
The text was updated successfully, but these errors were encountered: