typescript - 如何编写接受实现接口(interface)的类作为参数的 TypeScript 函数?

标签 typescript class interface

我想编写一个接受类作为参数的函数,但只接受实现特定接口(interface)的类。

我知道我可以使用 any,但是依靠类型系统来强制执行这一点会很好。

一些伪代码来表达我的意思......

interface MyInterface { ... }
class Class1 implements MyInterface { ... }
class Class2 { ... }

function doStuff(classParameter: Class implements MyInterface) { ... }
doStuff(Class1); // OK
doStuff(Class2); // Error

最佳答案

您可以使用构造函数签名来强制执行构造函数将返回与接口(interface)兼容的实例这一事实。您可以将它用作通用参数约束或直接用作参数,具体取决于您需要对类执行的操作:

interface MyInterface { foo: number }
class Class1 implements MyInterface { foo: number }
class Class2 { bar: number }

function doStuff0(classParameter: new (...args: any[]) => MyInterface) { }
doStuff0(Class1); // OK
doStuff0(Class2); // Error

function doStuff1<T  extends new (...args: any[]) => MyInterface>(classParameter: T) {  }
doStuff1(Class1); // OK
doStuff1(Class2); // Error

注意 我在示例中添加了成员​​,不要忘记 Typescript 使用结构类型系统,因此兼容性由成员而不是 implements MyInterface 决定声明,所以如果 MyInterface 任何类都是兼容的是空的,如果一个类有 foo,它就是兼容的成员,即使它没有明确声明 implements MyInterface

关于typescript - 如何编写接受实现接口(interface)的类作为参数的 TypeScript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52555937/

相关文章:

angular - ionic 3 可排序网格或表格

c++ - 了解构造函数定义 block 的句法变体

c# - 方法返回默认值

c++ - 在另一个类的声明中将参数传递给类构造函数

pointers - 覆盖接口(interface)指针值

interface - 在 SystemVerilog 中为接口(interface)内的接口(interface)指定 modport

javascript - typescript:从条件类型派生类型

Visual Studio 2017 中的 Angular 5 看不到文件更改

javascript - VSCode 仅在某处导入时通过相应的 Foo.d.ts 为 Foo.js 提供智能感知;如何在 Foo.js 本身中启用智能感知?

python - 让父函数返回 - super 返回?