Home > Blockchain >  Why does () => void return something?
Why does () => void return something?

Time:03-29

I know that below does NOT mean the return 'type' is void. What I understood is that voidFunc returns nothing since it is returning 'void'. Why does it return any type?

type voidFunc = () => void

const myFunc: voidFunc = () => {
  return 'hello'
}

How is it different from writing it as below? type voidFunc = () => any

CodePudding user response:

See Assignability of Functions

Return type void

The void return type for functions can produce some unusual, but expected behavior.

Contextual typing with a return type of void does not force functions to not return something. Another way to say this is a contextual function type with a void return type (type vf = () => void), when implemented, can return any other value, but it will be ignored.

Thus, the following implementations of the type () => void are valid:

type voidFunc = () => void;
 
const f1: voidFunc = () => {
  return true;
};
 
const f2: voidFunc = () => true;
 
const f3: voidFunc = function () {
  return true;
};

And when the return value of one of these functions is assigned to another variable, it will retain the type of void:

const v1 = f1();
 
const v2 = f2();
 
const v3 = f3();
  • Related