在typescript中,如何获取到对象的类型?

在写代码时 想根据对象或数组来生成一些常量类型。比如:

const obj = {
    dev_server: 'http://dev_server/',
    prod_server: 'https://prod_server/',
    stage_server: 'https://stage_server/'
}

type KeyProps = ?

期待的keyProps的是dev_server | prod_server | stage_serverhttp://dev_server/ | https://prod_server/ | https://stage_server/

const arr = [
    {label: 'dev', value: 'dev'},
    {label: 'prod', value: 'prod'},
    {label: 'stage', value: 'stage'},
]
type KeyProps = ?

期待的KeyProps的是dev | prod | stage
应该怎么定义这几个的类型呢? 请论坛内大神指教指教~

阅读 1.8k
2 个回答
const obj = {
  dev_server: 'http://dev_server/',
  prod_server: 'https://prod_server/',
  stage_server: 'https://stage_server/'
} as const

type KeyProps = keyof typeof obj

type ValueProps = typeof obj[KeyProps]

const arr = [
  {label: 'dev', value: 'dev'},
  {label: 'prod', value: 'prod'},
  {label: 'stage', value: 'stage'},
] as const

type KeyLabelProps = typeof arr[number]['label']

这样处理是可以的

const obj = {
  dev_server: "http://dev_server/",
  prod_server: "https://prod_server/",
  stage_server: "https://stage_server/",
} as const;

type KeyProps = keyof typeof obj | typeof obj[keyof typeof obj];

const arr = [
  { label: "dev", value: "dev" },
  { label: "prod", value: "prod" },
  { label: "stage", value: "stage" },
] as const;

type KeyProps2 = typeof arr[number]["label"] | typeof arr[number]["value"];
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题