1

Let's say I have the following interface:

interface MyFunctionType {
  (text: string): string;
};

And the following function:

function myFunction(text) {
  const newText = "new" + text;
  return newText;
}

How do I define myFunction as being MyFunctionType?

I have previously been using arrow functions to get over this hurdle, such as:

const myFunction: MyFunctionType = (text) => {
  const newText = "new" + text;
  return newText;
}

Which works fine, however I'd prefer to use normal functions instead of arrow functions for clarity. I'd prefer not to inline the types, such as:

function myFunction(text: string): string {
  const newText = "new" + text;
  return newText;
}

How can I do this?

I've tried the following which doesn't work:

function myFunction(text): MyFunctionType {
  const newText = "new" + text;
  return newText;
}

function myFunction<MyFunctionType>(text) {
  const newText = "new" + text;
  return newText;
}

1 Answer 1

1

Use let - you are enforcing the type of the variable to hold the function.

The Typescript manual has a nice example:

interface SearchFunc {
   (source: string, subString: string): boolean;
}

let mySearch: SearchFunc; 
mySearch = function(source: string, subString: string) {
    let result = source.search(subString);
    return result > -1; 
}

You define a function interface as you did, and then you can use let to declare the function type.

And without let, you again enforce the type on the variable rather than the function object:

var mySearch: SearchFunc = function(source: string, subString: string) {
    let result = source.search(subString);
    return result > -1; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

OK, thank you. Unfortunately this is even less clear than simply using arrow functions, so it seems like my best option is just to stick with arrow functions for everything.
@Jake added another option!

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.