Typescript: `undefined` return type requires explicit return

Created on 19 Aug 2020  路  4Comments  路  Source: microsoft/TypeScript


TypeScript Version: playground


Search Terms: undefined return type

Code

function test(): undefined {
  console.log("hey")
}

Expected behavior: This should be allowed.

Actual behavior: TS requires the return type to be void or any.

Playground Link: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABFApgZygCgJQC5HgAmKwMYKhiA3gFCKIQJpwA2KAdC3AOaYBEACxQBPPthoBfIA

Most helpful comment

void return type is not undefined. ok, javascript is so useless and badly thought that returning nothing and returning undefined are the same, but they are not at least not in typescript. undefined === void returns a syntax error. And that is because undefined is anyway something and not the absolute nothingness that is represented by void.

All 4 comments

void return type is not undefined. ok, javascript is so useless and badly thought that returning nothing and returning undefined are the same, but they are not at least not in typescript. undefined === void returns a syntax error. And that is because undefined is anyway something and not the absolute nothingness that is represented by void.

I think this might be a duplicate of #36288.

Given the behavior of

function test(): void {
  return undefined;
}

I think @saschanaz has a point, FWIW.

undefined === void returns a syntax error. And that is because undefined is anyway something and not the absolute nothingness that is represented by void.

AFAIK that's not because undefined is an actual value, it's because void is null | undefined (without --strictNullCheck) and thus it's inappropriate to blindly assign void to undefined.

I agree that this is a duplicate, closing.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

uber5001 picture uber5001  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

jbondc picture jbondc  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments