Search code examples
typescriptunion-types

Returning an implicit type type of a Union in TypeScript


I am taking a course in TypeScript and the following code is supposed to return the implicit type of a union of 10 and the string literal “test”: 10 | "test". Can someone explain to me how? When I run it, the output I get is just 10 by itself. Or am I misunderstanding it?

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

Solution

  • 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.