I need to determine the type of a property from a predefined constant.
const my_constant = {
user: {
props: {
name: {
type: 'string'
}
}
},
media: {
props: {
id: {
type: 'number'
}
}
}
} as const;
type Name = keyof typeof my_constant;
type Constructed<T extends Name> = {
[K in keyof typeof my_constant[T]['props']]: typeof my_constant[T]['props'][K]['type']
// ~~~ Type '"type"' cannot be used to index type ...
}
I'm puzzled by why I can't use "type" as an index but am able to use "props".
If TypeScript can figure out that there is always a "props" attribute, why can't it infer that there is always a "type"?
Is there another approach to obtain the type?
My goal is to achieve something like this:
const user:Constructed<'user'> = {
name: 'John'
}
const media:Constructed<'media'> = {
id: 123
}
const user2:Constructed<'user'> = {
name: 444
// ~~~ Error
}
const media2:Constructed<'media'> = {
id: 'something'
// ~~~ Error
}
Here is the playground link with the exact error: