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

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

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

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

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

阅读 4.8k
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>;