Reputation: 6114
Just starting out with Typescript, and using interfaces for my functions, like so:
interface StringFunction {
(arg1:string):string
}
I can attach that interface to a function if I declare it as a variable:
let testFunction:StringFunction = function(arg1) {}
but I can't work out how I would (or can?) do it with a named function. This doesn't work:
function testFunction:StringFunction(arg1) {}
is there any way to do this?
Upvotes: 3
Views: 2151
Reputation: 2741
You can do it but the syntax is a bit different for named functions.
interface StringFunction {
(arg1:string): string
}
<StringFunction>function testFunction(arg1) {}
Here we cast testFunction
to the interface. arg1
will be a string
.
Make sure the type is before the function
keyword.
Upvotes: 8
Reputation: 250882
The need to explicitly state which interface is being used is a constraint of a nominal type system. TypeScript is structurally typed, so you don't need a way to explicitly state that your function implements the interface.
For example, the testFunction
below is perfectly acceptable where a StringFunction
is needed - and the compiler checks that it is.
interface StringFunction {
(arg1:string):string
}
function testFunction(arg1) { return ''; }
var x: StringFunction = testFunction;
The following example is to illustrate that type checking occurs:
interface StringFunction {
(arg1:string):string
}
function testFunction(arg1) { return 1; }
var x: StringFunction = testFunction; // Error
In this case, testFunction
is not compatible and the compiler issues a warning.
Additional notes:
In strict mode, your original function will indeed need type information (but the answer still applies).
function testFunction(arg1: string) { return ''; }
This is only needed where there is no context to infer the types, so the following works in strict mode even though it looks like it is missing a type annotation. The string
type on arg1
is a contextual type.
var x: StringFunction = (arg1) => { return ''; };
Upvotes: 2