Adding types

INPUT · Slides

Adding types to functions

01 / 05

The type goes after the parameter

A function parameter takes a type after a :, just like a variable.

Write this and passing in the wrong kind of value becomes an error where you called it. You do not have to go hunting inside the function.

function greet(personName: string) {  console.log("Hello, " + personName);}greet("Yui");

Result

Hello, Yui

02 / 05

Leave a parameter type off and you get told

TypeScript lets you know when you forget the type on a parameter. That is the message "Parameter 'personName' implicitly has an 'any' type".

any means "any type at all", and allowing it takes away the point of writing types in the first place. So always write a type on your parameters.

function greet(personName) {  console.log(personName);}

Result

Type error: Parameter 'personName' implicitly has an 'any' type.

03 / 05

The type of what comes back goes after the )

If a function gives a value back, its type goes after the closing bracket of the parameters.

The order is function name(parameters): return type {. Write it here and returning the wrong kind becomes an error inside the function.

function add(a: number, b: number): number {  return a + b;}console.log(add(3, 4));

Result

7

04 / 05

If nothing comes back, write void

For a function that only shows something and gives nothing back, write void. It means "there is no value coming back".

It runs without it, but writing it tells whoever reads it that you meant this function to return nothing.

function announce(word: string): void {  console.log("[Notice] " + word);}announce("no school tomorrow");

Result

[Notice] no school tomorrow

05 / 05

Passing the wrong thing shows up right there

Pass a string to a function that takes a number and it is an error on the line where you called it.

In JavaScript it would just run, and you would not notice until something odd like "32" came out. With a type written down, it stops here.

function twice(n: number): number {  return n * 2;}console.log(twice("3"));

Result

Type error: Argument of type 'string' is not assignable to parameter of type 'number'.