Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enforce a function type interface on a class method in typescript?

Tags:

typescript

Many methods of the class I'm writing implicitly have the same function type. What I want to do is enforce this function type so that I can explicitly state that certain methods must conform to the function type.

e.g.

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

and my class has some methods that conform to this interface.

class MyClass {
    // ...

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

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

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

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

    // ...
}

I know that someMethodThatConforms and anotherMethodThatConforms conform to the interface but now I want to know how do I assert that someMethodThatConforms and anotherMethodThatConforms must conform the interface MyFunctionType (so that if I change, MyFunctionType errors are thrown)?

like image 744
Rico Kahler Avatar asked Jun 01 '17 10:06

Rico Kahler


Video Answer


2 Answers

Here is the another way If you don't want to create another interface

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

class MyClass {
    // ...

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

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

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

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

    // ...
}
like image 63
RKS_Code Avatar answered Oct 31 '22 02:10

RKS_Code


We can define another interface and have MyClass implement it:

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;
    }
}

A more complex way: use mapped type to create a generic 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
}
like image 22
Jokester Avatar answered Oct 31 '22 02:10

Jokester