Typescript 尝试键入嵌套对象时,类型不能用于索引类型
问题的代码沙盒: 我有一个对象,它保存我的应用程序中使用的图像的数据,类似这样Typescript 尝试键入嵌套对象时,类型不能用于索引类型,typescript,Typescript,问题的代码沙盒: 我有一个对象,它保存我的应用程序中使用的图像的数据,类似这样 const IMAGES = { backgrounds: { stone: { source: require('assets/stone.jpg'), width: 40, height: 50 } }, buttons: { green: { source: require('assets/green.jpg'),
const IMAGES = {
backgrounds: {
stone: {
source: require('assets/stone.jpg'),
width: 40,
height: 50
}
},
buttons: {
green: {
source: require('assets/green.jpg'),
width: 20,
height: 5
}
}
}
export async function preloadImages<C extends keyof ImagesState, A extends keyof ImagesState[C]>(
category: C,
names: A[]
) {
names.forEach(name => console.log(IMAGES[category][name].source))
}
然后我有一个helper函数,它预加载这些资源并将它们存储在全局状态中,这个全局状态有以下类型定义(Texture
type这里是一个特殊的预加载资源,我认为它与问题无关)
接口图像状态{
背景:记录;
按钮:记录;
}
最后,我正在开发一个函数来预加载目前看起来像这样的资产
const IMAGES = {
backgrounds: {
stone: {
source: require('assets/stone.jpg'),
width: 40,
height: 50
}
},
buttons: {
green: {
source: require('assets/green.jpg'),
width: 20,
height: 5
}
}
}
export async function preloadImages<C extends keyof ImagesState, A extends keyof ImagesState[C]>(
category: C,
names: A[]
) {
names.forEach(name => console.log(IMAGES[category][name].source))
}
导出异步函数预加载映像(
类别:C,
姓名:A[]
) {
name.forEach(name=>console.log(图像[category][name].source))
}
这个函数的思想是这样的preload图像('backgrounds',['stone'])
,并为第一个参数提供自动完成,然后根据第一个参数提供第二个参数。现在我在IMAGES[category][name]
上遇到一个错误
类型“A”不能用于索引类型“{backgrounds:{
斯通:
我可以将像
C extends keyof ImagesState
这样的东西替换为C extends keyof IMAGES
,它可以工作,但是这个函数需要从state继承这些类型,因为它以后会进一步使用它。你找到解决方案了吗?