Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a return type of void for a function in a Typescript interface?

Tags:

I have this function:

   network = (action): void =>{
        if (action) {
            this.action = action;
            this.net = true;
            this.netd = true;
        } else {
            this.action = null;
            this.net = false;
            this.netd = false;
        }
    }

I tried to define an interface but it's not working for me:

interface IStateService {
    network: (action: string): void;
}

I get a message saying "unexpected token" on void

like image 687
Alan2 Avatar asked Jul 28 '14 05:07

Alan2


People also ask

What is void return type in TypeScript?

According to the TypeScript docs: void represents the return value of functions which don't return a value. Whenever you see a function returning void , you are explicitly told there is no return value. All functions with no return value have an inferred return type of void .

How do I specify a return type of function in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.

How do I assign a void in TypeScript?

TypeScript Data Type - Void Similar to languages like Java, void is used where there is no data. For example, if a function does not return any value then you can specify void as return type. There is no meaning to assign void to a variable, as only null or undefined is assignable to void.

How would you define a function type in TypeScript interface?

TypeScript Interface can be used to define a function type by ensuring a function signature. We use the optional property using a question mark before the property name colon. This optional property indicates that objects belonging to the Interface may or may not have to define these properties.


1 Answers

You have two options for syntax for a function-typed interface member, which are equivalent here:

interface IStateService {
    network: (action: string) => void;
}

or

interface IStateService {
    network(action: string): void;
}
like image 187
Ryan Cavanaugh Avatar answered Nov 13 '22 03:11

Ryan Cavanaugh