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)?
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() { /*...*/}
// ...
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With