ed'
ed'

Reputation: 1905

Specify a function's type inline with typescript

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.

Upvotes: 1

Views: 9917

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250246

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; 
    }
}

Upvotes: 1

Related Questions