Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does () => void return something?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading