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

The infer keyword

In the preceding section, we have defined the Flatten type. However, this behavior was hardcoded to return a number when an array of one dimension is provided. This means that the flatten type only works as expected with arrays of numbers. Fortunately, since the TypeScript 2.8 release, we can use the infer keyword to overcome this limitation:

type TypedFlatten<T> = T extends Array<infer U> ? U : T;

The infer keyword can be used in other scenarios. For example, we can use it to infer the return type of a function:

type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;type func1 = () => number;type returnOfFunc1 = ReturnType<func1>; // number
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