Typescript可以用泛型动态定义Interface或Type的key吗?

如下,就想实现一个动态Key的需求:

interface Apple<T> {
  [T]: string
}

type Apple<T extends string> = {
  [T]: string
}

感觉理论可以,一直又搞不出来。。。给力的大佬麻烦指点一二,谢谢~

阅读 4.6k
3 个回答

interface Apple<T extends any[]> {
    [P of T]: string
}

印象中好像可以这样写?没有上机测

interface myObjInterface {
  [key: string]: string
}

let data: myObjInterface = {
  'haha': '1313',
  2: '1313',
}

测试如下:
image.png

你想要这种效果?

image.png

写复杂了,直接用 Record 就可以

type Mine = Record<"name" | "age" | "sex", object>;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进