【问题标题】:How to specify that a property type must extend another type?如何指定一个属性类型必须扩展另一个类型?
【发布时间】:2021-04-07 02:39:29
【问题描述】:

我正在尝试声明一个类型,它应该只接受扩展另一种类型的对象。

例如:

export interface A extends B {
  aProp: string;
}

export interface B {
  bProp: string;
  // Feels wrong but how to tell something like ReadonlyArray<subClass extends B>?
  // I need children to contain A (or anything that extends B) & B properties
  children: ReadonlyArray<any & B>;
  childrenThatDoesntWork: ReadonlyArray<any extends B>; // <-- error here
}

class SomeClass {
  fun(obj: any extends B) { // <-- error '?' expected

  }
}

如何做到这一点?

谢谢!

【问题讨论】:

  • any 是你想要绕过类型检查时使用的类型,做any &amp; T 是没用的,它意味着any 最后。 any extends T 也没有任何意义
  • 是的,但绕过类型检查是我试图避免的。任何解决方案?

标签: typescript generics types interface extends


【解决方案1】:

这是我的解决方案:

export interface A extends B {
    aProp: string;
}

export interface B {
    bProp: string;
    // Feels wrong but how to tell something like ReadonlyArray<subClass extends B>?
    // I need children to contain A (or anything that extends B) & B properties
    children: ReadonlyArray<A | B>;
    childrenThatDoesntWork: ReadonlyArray<B>; 
}

class SomeClass {
    fun<T extends B>(obj: T) { 

    }
}

请检查它是否适用于您的情况。如果没有,请提供测试代码

【讨论】:

  • 我正在努力实现任何东西都可以扩展 B,所以 A | B 不是解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 2022-12-19
  • 2015-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多