1

In Typescript, we can have a function implement an interface like this:

interface ISample {
    (argument: boolean): number
}

let v: ISample;
v = function (isTrue: boolean): number {
    return 10;
}

But that applies only to functions created via function expressions (that is, initializing them through a variable, in this case it's v). When I try to do something similar to a function statement, it doesn't work:

interface ISample {
    (argument: boolean): number
}

function v: ISample (isTrue: boolean): number {
    return 10;
} // Doesn't work, compiler says '"(" expected'

So, is there a way to do that with function statements or tough luck, I'll have to ditch interface functions or use function expressions instead? Thanks!

2 Answers 2

2

The interface is there so you can require that variables or parameters or fields conform to the interface. You can declare the function using a function statement and then assign it anywhere an ISample is required.

interface ISample {
    (argument: boolean): number
}

function v(isTrue: boolean): number {
    return 10;
} 
let weNeedSample: ISample = v;

You can't force a function statement to conform to an interface in current typescript syntax. You will only get an error whenever you try to assign the function to a symbol of type ISample.

This is also what happens when you use a function expression. In this case the error occurs because you perform the assignment to a variable of type ISample, if you had just the function expression (such as with an IFFE) you couldn't specify that that must conform to the interface either.

Sign up to request clarification or add additional context in comments.

3 Comments

So, the suggestion is that I should do the statement, then assign it to a variable that implements the interface in order to test against it?
@Rafael You could do that, but the question is why do you want it to conform to the interface? Probably because somewhere in the code you will actually try to assign it to a variable of this type, and that is where you will get the error.
@Rafael added some more explanations
2

You can cast the function delcaration to the interface like so

interface ISample {
  (argument: boolean): number
}

<ISample>function v(isTrue) { // isTrue is a boolean and return type is number
  return 10;
}

1 Comment

Nice trick. But currently TypeScript gets confused and reports an error when trying to use such function: playground example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.