Guard your functions with types

INPUT · Slides

Parameters you can leave out

01 / 05

Too few arguments and you get told off

A function like the ones you made in chapter 1 gives you an error if you call it without an argument. TypeScript watches even the number of arguments.

"Expected 1 arguments, but got 0." is what that looks like.

function call(name: string): void {  console.log("Hi, " + name);}call();

Result

Type error: Expected 1 arguments, but got 0.

02 / 05

Add a ? and it can be left out

Put a ? after the name of a parameter and it becomes "an argument you do not have to pass". Calling without it is no longer an error.

In exchange, when you leave it out what is inside is undefined. Have a look at the second call below.

function call(name?: string): void {  console.log(name);}call("Yui");call();

Result

Yui
undefined

03 / 05

Inside, think about "it might not be there"

The type of a parameter with a ? becomes, inside, "that type or undefined". So trying to use it in a sum as it is gets stopped.

"'b' is possibly 'undefined'." is saying exactly that. It is not getting in your way — it is showing you up front the place that breaks when someone calls without it.

function add(a: number, b?: number): number {  return a + b;}

Result

Type error: 'b' is possibly 'undefined'.

04 / 05

Check it, then use it

The fix is the narrowing you did in chapter 3. Look at whether it is undefined first and you can use it happily afterwards.

Once past the if, b is a number as far as TypeScript is concerned.

function add(a: number, b?: number): number {  if (b === undefined) {    return a;  }  return a + b;}console.log(add(5));console.log(add(5, 3));

Result

5
8

05 / 05

A default parameter saves you the worry

There is another way. Decide with = what the value should be when it is left out. Written like that, there is always a value inside, so undefined never comes up.

You do not write the ?. Writing = "Hi" already means "this can be left out".

If you can settle on a value for when it is missing, this is the more straightforward one. Right, have a go at both.

function call(  name: string,  greeting: string = "Hi"): void {  console.log(greeting + ", " + name);}call("Yui");call("Yui", "Hello");

Result

Hi, Yui
Hello, Yui