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

Control flow analysis

TypeScript includes a feature known as control flow analysis that is used to identify the type of a variable, based on the execution flow of a program. This feature allows TypeScript to have more precise type inference capabilities.

The following example defines a function that takes two arguments, and the type of one of them (named value) is the union type of number and array of number:

function increment(  incrementBy: number, value: number | number[]) {  if (Array.isArray(value)) {    // value must be an array of number    return value.map(value => value + incrementBy);  } else {    // value is a number    return value + incrementBy;  }}increment(2, 2); // 4increment(2, [2, 4, 6]); // [4, 6, 8]

Within the body of the function, we ...

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