如何在打字稿中的类方法上强制执行函数类型接口?

里科·卡勒(Rico Kahler)

class我正在编写的许多方法都隐式具有相同的函数类型我要执行的是强制执行此函数类型,以便我可以明确声明某些方法必须符合该函数类型。

例如

interface MyFunctionType {(resource: string | Resource): Something}

而且我的课有一些符合该接口的方法。

class MyClass {
    // ...

    someMethod() { /*...*/ }

    someMethodThatConforms(resource: string | Resource) {
        // ...
        return new Something(/*...*/);
    }

    anotherMethodThatConforms(resource: string | Resource) {
        // ...
        return new Something(/*...*/);
    }

    someOtherMethod() { /*...*/ }

    // ...
}

我知道,someMethodThatConformsanotherMethodThatConforms符合该接口,但现在我想知道我怎么断言someMethodThatConformsanotherMethodThatConforms必须符合该接口MyFunctionType(所以,如果我改变,MyFunctionType错误抛出)?

笑话

我们可以定义另一个接口并MyClass实现它:

interface MyFunctionType {(resource: string | Resource): Something}

interface FixedMethods {
    someMethodThatConforms: MyFunctionType;
    // you can add more
}

class MyClass implements FixedMethods {
    someMethodThatConforms(resource: string | Resource) {
        // this method will fail type check, until we return a Something
        return 1;
    }
}

一种更复杂的方法:用于mapped type创建泛型类型:

interface MyFunctionType { (resource: string | Resource): Something }

// a Mapped Type to fix methods, used in place of a interface
type FixedMethods<T extends string> = {
    [k in T]: MyFunctionType
}

class MyClass implements FixedMethods<"someMethodThatConforms" | "anotherMethodThatConforms"> {
    someMethodThatConforms(resource: string | Resource) {
        // this method will fail type check, until we return a Something
        return 1;
    }

    // it also complains about lack of "anotherMethodThatConforms" method
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在打字稿中强制执行功能类型

如何在打字稿eslint中强制执行文件名和文件夹名称约定?

如何在打字稿中强制变量的类型?

如何在打字稿中强制转换此函数类型

如何通过其实现的接口在具体类中强制执行类型构造函数?

如何在打字稿中强制覆盖方法的返回类型?

如何在打字稿中获取方法返回类型

如何在打字稿3.0中强制接口实现枚举的“实现”键?

如何在打字稿中强制使用类型实例而不是 typeof

如何在打字稿中定义通用接口

如何在打字稿中定义匿名通用接口?

如何在打字稿中实现具有多个匿名函数的接口

如何在打字稿中使用函数参数类型?

打字稿基于模板变量强制执行函数返回类型

如何在打字稿的函数中检查类型联合的类型

如何在打字稿中编写匿名函数的函数类型定义?

使用类的方法在打字稿中创建联合类型

如何在PHP中强制执行类型提示接口协定

在打字稿中声明函数类型的不同方法?

如何在打字稿中检索 T 类型的泛型类的名称

如何在打字稿函数中声明类型为 number 的局部变量?

您如何在打字稿中定义同时属于对象和函数的类型?

如何在打字稿中制作一种类型的函数链(数组)?

如何在打字稿中的对象中使用类函数?

在打字稿函数中声明“ this”的类型?

如何在打字稿中定义对象类型的对象

如何在打字稿中获得“这个”类型

如何在打字稿中公开API返回的类型

如何在打字稿中向`... args`添加类型