typescript如何定义 arr 的类型?

如下,想知道怎么定义arr的类型

type Tag = 'xxx'|'xxx'|'xx'

interface More {
    one: boolean
    two: string
}

const tag:Tag = 'xxx'
const more:More = {
    one: true,
    two: 'xx'
}

const tagInfo = {
    more
}

//如何定义这个的类型
const arr = [
    {
        tag,
        ...tagInfo[tag]
    }
]
阅读 1.9k
3 个回答

想到了一个解决方案

type TagInfo = typeof tagInfo

type TagProperty<T extends Tag> = {
    tag: T
} & {
    [key in keyof TagInfo[T]]: TagInfo[T][key]
}

type ArrItem = TagProperty<'xx'>|TagProperty<'xxx'>
type Arr = ArrItem[]

你的 const tagInfo 我没看懂,照你下面把 tag 当索引取了 tagInfo 的值,tagInfo 的类型不应该是这样的么

const tagInfo = {
    xxx: more
}

如果是这样,ts 会给 tagInfo 自动推导出类型,arr 也会自动推导出类型
可以参考这个ts演练场

type Tag = 'more' | 'xxx' | 'xx'

interface More {
  one: boolean
  two: string
}

const tag: Tag = 'more'
const more: More = {
  one: true,
  two: 'xx'
}

const tagInfo: Partial<Record<Tag, More>> = {
  more: more,
}

type ArrItem<T> = T & {
  tag: Tag;
};

const arr: ArrItem<More>[] = [
  {
    tag,
    ...tagInfo[tag]
  }
]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题