有没有一种方法可以从接口属性中提取数组类型的通用类型?

时间:2019-08-10 10:32:32

标签: typescript

我说我有这样的东西。
我想从number | string的objects属性中取出A部分,并在B中重用它。


interface A {
  objects: Array<number | string>
}

interface B{
          // I want to extract this part from the objects of the "A" interface
  object: number | string  
}

我能想到这样的东西


type ObjectType = number | string

interface A {
  objects: Array<ObjectType>
}

interface B{
  object: ObjectType
}

但是我真正想要的是这样的东西


interface A {
  objects: Array<number | string>
}

interface B{
          // I am making this up, but is there something like this in Typescript??
  object: ExtractType<A, "objects">
}


1 个答案:

答案 0 :(得分:1)

您可以借助type inference in conditional types推断数组的项目类型:

type ArrayItemType<T extends Array<any>> = T extends Array<infer I> ? I : any

interface A {
  objects: Array<number | string>
}

interface B{
  // (property) B.object: string | number
  object: ArrayItemType<A["objects"]>
}

Playground