尝试键入嵌套对象时,类型不能用于索引类型

时间:2020-08-12 08:43:46

标签: typescript

此问题的代码和框:https://codesandbox.io/s/agitated-hugle-3k15n?file=/src/index.ts

我有一个对象,可以保存我的应用程序中使用的图像数据

const IMAGES = {
  backgrounds: {
    stone: {
      source: require('assets/stone.jpg'),
      width: 40,
      height: 50
    }
  },
  buttons: {
    green: {
      source: require('assets/green.jpg'),
      width: 20,
      height: 5
    }
  }
}

然后我有一个帮助程序功能,可以预加载这些资产并将其存储在全局状态中,此全局状态具有以下类型定义(Texture类型是一种特殊的预加载资产,我不认为这是相关的问题)

interface ImagesState {
  backgrounds: Record<keyof typeof IMAGES['backgrounds'], Texture>;
  buttons: Record<keyof typeof IMAGES['buttons'], Texture>;
}

最后,我正在开发一个函数来预载当前看起来像这样的资产


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))

}

此函数的想法是看起来像preloadImages('backgrounds', ['stone'])并为第一个参数提供自动完成功能,然后根据第一个参数提供第二个参数的自动完成功能。现在,我在IMAGES[category][name]处收到一条错误消息,表示正在关注

类型'A'不能用于索引类型'{ 石头:...

我可以将C extends keyof ImagesState之类的东西替换为C extends keyof IMAGES并可以工作,但是此函数需要从状态继承这些类型,因为它在以后的工作中会进一步工作。

0 个答案:

没有答案