【问题标题】:TypeScript: type of class that implements a certain interface or methodTypeScript:实现某个接口或方法的类的类型
【发布时间】:2022-01-22 03:27:14
【问题描述】:

目标

我想要一个描述具有以下类型值的对象的类型:Array<ClassRef> 其中ClassRef 是任何必须实现某个接口的类。

方法

type KeyClassMap<SomeUnionType> = {
   [key in keyof SomeUnionType]: Array<ClassRef>
} 

type ClassRef = new (...args: any[]) => any // should extend that interface

interface I {
   [Symbol.hasInstance](hint: string): boolean
}

const _map: KeyClassMap<UnionType> = {
   myKey: [Date, MyOwnClass, MyOtherClass] // <- all these should have implemented Symbol.hasInstance to check with `instanceof` operator
}

问题

该示例缺少实现该接口的类的声明。我不知道该怎么做。

每个类只应实现这一方法 ([Symbol.hasInstance]) 以检查值是否是该类的实例。

我想知道如何声明实现该接口的类的类型或任何其他方式来描述具有此方法的类。

我认为这是不可能的,所以我很感激任何其他提示。

【问题讨论】:

  • _map 是否可能是KeyClassMap&lt;Whatever&gt; 类型?如果不是,我不太确定你的意思。
  • 哦,是的,谢谢@Grochni!

标签: javascript typescript


【解决方案1】:

在定义ClassRef 类型时,您实际上是在指定其构造函数的类型。由于构造函数返回类的实例,您可以通过强制其构造函数的返回值实现该接口来强制该类实现特定接口。您的代码应如下所示:

type ClassRef<T> = new (...args: any[]) => T;

type KeyClassMap<SomeUnionType> = {
   [key in keyof SomeUnionType]: Array<ClassRef<I>>
} 

如果您也想在其他地方使用KeyClassMap 类型,当然可以为其添加另一个泛型,而不是静态使用I 接口。

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 2019-06-27
    • 2019-05-09
    • 2017-11-06
    • 2011-05-16
    • 2015-10-08
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多