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
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 .
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With