Reputation: 8846
I can define the interface of a function:
interface Handler {
(state: IState, action: IAction): IState;
}
Then I can declare a function that satisfies the interface:
let selectRegimen: Handler = function(state, action) {
return state;
};
But what about named (as in, not anonymous) function? Obviously, I could do something like this:
let selectRegimen: Handler = function selectRegiment(state, action) {
return state;
};
...but something feels strange about that syntax. Is there a better way to handle this?
Upvotes: 2
Views: 3995
Reputation: 2283
You can do this
// This is where you define the function
export interface SomeInterfaceName{
someFunctionName(someParamName: SomeParameterType): SomeReturnType;
}
// Somewhere on the code
// This is where you implement the function
const someObjectThatImplemntsTheInterface = {
someFunctionName: function(someParamName: SomeType) {
return SomeReturnType;
}
} as SomeInterfaceName;
// or you can implement with arrow function
const someObjectThatImplemntsTheInterface1 = {
someFunctionName: (someParamName: SomeType) => {
return SomeReturnType;
}
} as SomeInterfaceName;
Upvotes: 0
Reputation: 198
FWIW I landed here looking to force a named function in a class by having it implement an interface.
To do this you can:
interface Handler {
selectRegimen: (state: IState, action: IAction) => IState
}
class MyHandler implements Handler {
selectRegimen (state: IState, action: IAction) {
let newState: IState
// ...
return newState
}
}
Upvotes: 7
Reputation: 106640
There's no way to force a specific name in a named function expression just like there's no way to force a specific variable name to assign the function to.
What you are doing is fine though you could use a type alias instead of an interface if you find that better suits your taste:
type Handler = (state: IState, action: IAction) => IState;
Upvotes: 6