我说我有这样的东西。
我想从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">
}
答案 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"]>
}