首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替代索引签名

替代索引签名
EN

Stack Overflow用户
提问于 2022-05-06 22:40:16
回答 1查看 39关注 0票数 0

我有一个像这样的对象数组:

代码语言:javascript
复制
[
  {
    "bio": "Douglas Gerald Hurley is an American engineer, former Marine Corps pilot and former NASA astronaut. He launched into space for the third time as commander of Crew Dragon Demo-2.",
    "images": {
      "png": "./assets/crew/image-douglas-hurley.png",
      "webp": "./assets/crew/image-douglas-hurley.webp"
    },
    "name": "Douglas Hurley",
    "role": "Commander"
  },
  {
    "bio": "Mark Richard Shuttleworth is the founder and CEO of Canonical, the company behind the Linux-based Ubuntu operating system. Shuttleworth became the first South African to travel to space as a space tourist.",
    "images": {
      "png": "./assets/crew/image-mark-shuttleworth.png",
      "webp": "./assets/crew/image-mark-shuttleworth.webp"
    },
    "name": "Mark Shuttleworth",
    "role": "Mission Specialist"
  },
  {
    "bio": "Pilot on the first operational flight of the SpaceX Crew Dragon to the International Space Station. Glover is a commander in the U.S. Navy where he pilots an F/A-18.He was a crew member of Expedition 64, and served as a station systems flight engineer.",
    "images": {
      "png": "./assets/crew/image-victor-glover.png",
      "webp": "./assets/crew/image-victor-glover.webp"
    },
    "name": "Victor Glover",
    "role": "Pilot"
  },
  {
    "bio": "Anousheh Ansari is an Iranian American engineer and co-founder of Prodea Systems. Ansari was the fourth self-funded space tourist, the first self-funded woman to fly to the ISS, and the first Iranian in space.",
    "images": {
      "png": "./assets/crew/image-anousheh-ansari.png",
      "webp": "./assets/crew/image-anousheh-ansari.webp"
    },
    "name": "Anousheh Ansari",
    "role": "Flight Engineer"
  }
]

我用索引签名输入了它:

代码语言:javascript
复制
    export type PlanetInfo = {
      [key: string]: string;
    }[];

当然,也有关键的“图像”是对象,我用以下方法来解决这个问题:

代码语言:javascript
复制
    export type PlanetInfo = {
          [key: string]: any;
        }[];

但我不认为“任何”的用法是正确的。有更好的办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-06 22:50:52

客观地回答你的问题,这是我要说的:

代码语言:javascript
复制
//if these are optional mark them so with `?` also if there are more formats you support you could add them here as well
type Image = {
 png: string,
 webp: string,
}
export type PlanetInfo = {
      [key: string]: string | Image;
    }[];

然而,我觉得你的类型比我们刚才定义的“自由”要少一些。那麽:

代码语言:javascript
复制
type PlanetInfo = {
        bio: string,
        images: Image //same type as above,
        name: string,
        role: string, //maybe this one is an enum (can have only a set of values, check the api documentation of wherever you're getting this value
}[]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72148043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档