-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Broken inference between index typed object and Record #14930
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
The reason this fails is that interface Errors {
[field: string]: {
key: string
message: string
};
} has no discrete keys. So the record is empty. The Consider const errors = { // no explicit type, inferred type has members, still compatible with interface.
password: {
key: 'minimumComplexity',
message: 'Password must contain at least one non alphanumeric character'
}
};
function genericObjectFunction<K extends string, V>(obj: Record<K, V>): [K, V][] {
return [];
};
const genericErrors = genericObjectFunction(errors); EDIT: interface Errors {
[field: string]: {
key: string
message: string
}
}
const errors: Errors = {
password: {
key: 'minimumComplexity',
message: 'Password must contain at least one non alphanumeric character'
}
};
function genericObjectFunction<K extends string, V>(obj: Record<K, V>): [K, V][];
function genericObjectFunction<V>(obj: { [field: string]: V }): [string,{[P in keyof V]:V[P]}][];
function genericObjectFunction<K extends string, V>(obj: Record<string, V>): [K, V][]{
return [];
};
const typeInferredErrors = {
password: {
key: 'minimumComplexity',
message: 'Password must contain at least one non alphanumeric character'
}
};
const genericErrorsX = genericObjectFunction(errors);
const genericErrorsY = genericObjectFunction(typeInferredErrors); |
Yes, I tried the overloads as a POC and it works. It's just a bit annoying to do that on dozens of functions :) I understand Record tries to extract information from explicit keys and values, but couldn't a simple translation exist between the two worlds? |
Possibly, but I feel like mixing the two could be error prone. It is also possible that this is a bug. I do not believe it is but I could certainly be wrong. |
This no longer produces an error as of v3.3.3. Playground link: v3.1.6, with error Should this be closed? |
TypeScript Version: 2.2.2
Code
The types seem generally compatible though, as expected this is legal:
Expected behavior:
genericObjectFunction(errors)
should compile.The text was updated successfully, but these errors were encountered: