Execute Program

TypeScript Basics: Functions

Welcome to the Functions lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • A function takes arguments, which have types. Then the function returns something, which also has a type. The types are marked with :, as they were for simple variables.

  • (Some examples in this lesson will cause a type error. For those, you should answer with type error.)

  • >
    function double(x: number): number {
    return 2 * x;
    }
    double(2);
    Result:
    4Pass Icon
  • >
    function double(x: number): number {
    return 2 * x;
    }
    double('anything');
    Result:
    type error: Argument of type 'string' is not assignable to parameter of type 'number'.Pass Icon
  • >
    function add1(n: number): number {
    return n + 1;
    }
    add1(2);
    Result:
    3Pass Icon
  • >
    function add1(n: number): number {
    return n + true;
    }
    add1(2);
    Result:
    type error: Operator '+' cannot be applied to types 'number' and 'boolean'.Pass Icon
  • The example above shows us the main reason that TypeScript exists. We'll probably never want to add true to a number. However, in JavaScript, 1 + true gives 2. We might not notice that kind of bug; it might make it all the way to production!

  • In TypeScript, that same 1 + true is a type error. This doesn't mean that 1 + true throws an error at runtime. Rather, 1 + true isn't a legal TypeScript program at all. It can never even begin executing.

  • There's an easy way to see this: a function can cause a type error even if it's never called.

  • >
    function add1(n: number): number {
    return n + true;
    }
    Result:
    type error: Operator '+' cannot be applied to types 'number' and 'boolean'.Pass Icon
  • Arrow functions work in basically the same way as normal functions. The function below is like the JavaScript function const add1 = n => n + 1.

  • >
    const add1 = (n: number): number => n + 1;
    add1(2);
    Result:
    3Pass Icon
  • >
    const add1 = (n: number): number => n + true;
    add1(2);
    Result:
    type error: Operator '+' cannot be applied to types 'number' and 'boolean'.Pass Icon