Returning an implicit type type of a Union in TypeScript

TypeScript gets compiled to JavaScript, and JavaScript (where the code runs and gives you the console.log output) has no concept of types – it runs just the plain JavaScript, which is:

function withImplicitReturnType(b) {
  if (b) {
    return 10;
  }
  return "test";
}
console.log(withImplicitReturnType(true));

The function, when called here, returns 10, so 10 gets logged.

The 10 | 'test' union type can only be seen in TypeScript, for example, in intellisense, but not in the running JavaScript after the code has been compiled.

enter image description here

If you wanted to use that union, remember that the union is only a type, so it’ll be useful for type-checking, but it will not exist in the emitted JavaScript code.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top