繁体   English   中英

如何推断扩展泛型类型的子属性类型?

[英]How can I infer the child property types of an extended Generic type?

我想编写一个返回扩展泛型类型属性的函数。 甚至有可能吗?

这是我尝试过的:

interface Animal {
    readonly weight: {total: number}
}

interface Dog extends Animal {
    readonly weight: {total: number, tail: number, head: number, body: number }
}


const getWeight = <T extends Animal>(animal: T) => {
    return animal.weight
}

const myDog = { weight: { total: 20, tail: 5, head: 5, body: 10 } }

const myDogsWeight = getWeight<Dog>(myDog)

// Property 'head' does not exist on type '{ total: number; }'.
const myDogsHeadWeight = myDogsWeight.head



如果我尝试显式注释函数的返回类型,则会收到另一个错误:

type InferredWeight<TAnimal> = TAnimal extends { readonly weight: infer U } ? U : never
type DogWeight = InferredWeight<Dog> // <-- This type works correctly

const getWeightTyped = <T extends Animal>(animal: T): InferredWeight<T> => {
    // Type '{ total: number; }' is not assignable to type 'InferredWeight<T>'.
    return animal.weight
}



这是一个游乐场链接

唯一似乎相关的 TypeScript Github 问题是this one ,但它是联合类型的问题。

正如@jcalz 在评论中提到的,您可以使用查找类型:

这应该做你正在寻找的。

interface Animal {
  readonly weight: { total: number }
}

interface Dog extends Animal {
  readonly weight: { total: number, tail: number, head: number, body: number }
}

const getWeight = <
  T extends Animal
>(animal: T): T['weight'] => {
  return animal.weight
}

const myDog = { weight: { total: 20, tail: 5, head: 5, body: 10 } }

const myDogsWeight = getWeight(myDog);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM