Typescript如何从常量属性值推断类型



我想从以前定义的常量中获取属性的类型。

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 ...
}

我不明白为什么我不能使用";类型";作为索引,但我可以使用";道具";。

如果typescript可以推断出;道具";归因于为什么它不能推断出总是存在";类型";?

有没有其他方法可以得到类型?

我想要实现的是这样的目标:


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
}

这是操场链接的确切错误:

游乐场链接

Typescript不能使用字符串对常量进行索引。它需要合适的钥匙。您可以检查对象是否具有属性CCD_ 1,也可以使用Mapped类型来获得真实类型;字符串";。

const my_constant = {
user: {
props: {
name: {
type: 'string'
}
}
},
media: {
props: {
id: {
type: 'number'
}
}
}
} as const;
type Name = keyof typeof my_constant;
type InferType<T> = T extends {type: infer I} ? I : never;
interface Mapped {
string: string;
number: number;
}
type Constructed<T extends Name> = {
[K in keyof typeof my_constant[T]['props']]: 
InferType<typeof my_constant[T]['props'][K]> extends keyof Mapped ?
Mapped[InferType<typeof my_constant[T]['props'][K]>] : never
}

游乐场链接

最新更新