Could anybody with a better understanding of TypeScript's type system explain to me why the following does not work?
export const mySchema = {
user: {
email: {type: 'string'},
name: {type: 'string'},
age: {type: 'number'},
},
message: {
user_id: {type: 'string'},
text: {type: 'string'},
},
} as const;
type TypeMap = {
string: string;
number: number;
};
// Causes an error
type Instance<TableName extends keyof typeof mySchema> = {
[Column in keyof typeof mySchema[TableName]]: TypeMap[typeof mySchema[TableName][Column]['type']];
};
// Totally fine
type UserInstance = {
[Column in keyof typeof mySchema['user']]: TypeMap[typeof mySchema['user'][Column]['type']];
};
For context I've been trying to create generic instance types for a const
object that represents a database schema.
In TypeScript 3.8.3, I see the following error:
Error:(19, 57) TS2536: Type '"type"' cannot be used to index type '{ readonly user: { readonly email: { readonly type: "string"; }; readonly name: { readonly type: "string"; }; readonly age: { readonly type: "number"; }; }; readonly message: { readonly user_id: { readonly type: "string"; }; readonly text: { ...; }; }; }[TableName][Column]'.
Why can't type
be used to index here, even though type
always exists?
Despite this, why is everything fine if I hard code TableName
instead?
Thanks in advance!