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:
4
>
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'.
>
function add1(n: number): number {return n + 1;}add1(2);Result:
3
>
function add1(n: number): number {return n + true;}add1(2);Result:
type error: Operator '+' cannot be applied to types 'number' and 'boolean'.
The example above shows us the main reason that TypeScript exists. We'll probably never want to add
trueto a number. However, in JavaScript,1 + truegives2. We might not notice that kind of bug; it might make it all the way to production!In TypeScript, that same
1 + trueis a type error. This doesn't mean that1 + truethrows an error at runtime. Rather,1 + trueisn'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'.
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:
3
>
const add1 = (n: number): number => n + true;add1(2);Result:
type error: Operator '+' cannot be applied to types 'number' and 'boolean'.