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 is the void implicit return type missing from my Typescript function?

Consider this function:

function foo(check: boolean){
  if(check){
    return 123;
  }
}

Why is the implicit return type only number rather than number | void?

Stackblitz: https://stackblitz.com/edit/typescript-jwy5xn?file=index.ts

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 :

The primary issue here seems to be that you are not using the --strictNullChecks compiler option, part of the --strict suite of compiler options that is more or less considered a "standard" set of type safety features and is strongly recommended.

With --strictNullChecks disabled, the values null and undefined are considered assignable to every other type, and get absorbed by them. Any operation that could return, say, number or undefined, will be shown as returning just number. Which is not great.

If you enable --strictNullChecks then you’ll see that the return type of your function is the union number | undefined, which would hopefully meet your needs.

(Note that number | undefined isn’t exactly the same as number | void. But the relationship between void and undefined is somewhat muddy and, I think, not directly related to why you only saw number, which I interpret as the real question. If you want to know more about that you can look at Why is undefined assignable to void? or Why does TypeScript have both `void` and `undefined`? etc.)

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