1

Is there a way in typescript to define the type of a function (note: not an arrow function) in typescript?

I'm aware of the following method:

const MyFunctionCreator = (): MyFunction => {
    return function(input) {
        return "";
    };
};

However, I am trying to set the type of a static function inside a class, so this is not ideal.

class MyClass {
    static function(input) {
        return "";
    }
}

Is there a way in the example above to do something like:

class MyClass {
    static myFunction: MyFunction(input) {
        return "";
    }

    static myFunction(input) {
        return "";
    } as MyFunction
}

I can of course re-type the param/return types every time, but I wish to share types across my classes.

2
  • Not sure what you are looking for here ? Why can't you just define the function signature when you declare it ? you can reuse the type using a type query. Commented Jul 17, 2018 at 10:27
  • I want to assign a type to the function as a whole, I do not want to re-define the signature every time I create an identical function elsewhere. Commented Jul 17, 2018 at 11:45

1 Answer 1

1

You can use a function field instead of a member. For static fields there is not much difference, for instance fields they get assigned every time you create an object so that might have performance implications of you create a lot of instances.

type MyFunction = (input : string) => number

class MyClass {
    static myFunction: MyFunction = function (input) {
        return input.length; // input is string
    }

    // error wrong return type
    static myFunctionError: MyFunction = function (input) {
        return input; 
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I know about arrow functions, what I want to know is if you can do it without an arrow function
It's not an arrow function, it's a function expression. But this is the only available option, 95% sure on this :)

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.