Skip to Content
Learning TypeScript 2.x - Second Edition
book

Learning TypeScript 2.x - Second Edition

by Remo H. Jansen
April 2018
Beginner content levelBeginner
536 pages
13h 21m
English
Packt Publishing
Content preview from Learning TypeScript 2.x - Second Edition

Functions with default parameters

When a function has some optional parameters, we must check whether an argument has been passed to the function (just like we did in the previous example) to prevent potential errors.

There are some scenarios where it would be more useful to provide a default value for a parameter when it is not supplied than making it an optional parameter. Let's rewrite the add function (from the previous section) using the inline if structure:

function add(foo: number, bar: number, foobar?: number): number { 
    return foo + bar + (foobar !== undefined ? foobar : 0); 
} 

There is nothing wrong with the preceding function, but we can improve its readability by providing a default value for the foobar parameter instead of using ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering TypeScript - Fourth Edition

Mastering TypeScript - Fourth Edition

Nathan Rozentals
Learning TypeScript

Learning TypeScript

Josh Goldberg
TypeScript for Beginners

TypeScript for Beginners

Bharath Thippireddy

Publisher Resources

ISBN: 9781788391474Supplemental Content