gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:09 25 4
gpt4 key购买 nike

我想编写一个接受类作为参数的函数,但只接受实现特定接口(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com