29,99 €
Start developing modern day component based web apps using React 16, Redux and TypeScript 3 with this easy to follow guide filled with practical examples.
Key Features
Learn the latest and core features of React such as components, React Router, and suspense
Dive into TypeScript 3 and it`s core components such as interfaces, types aliases, tuples, generics and much more.
Build small-to-large scale single page applications with React, Redux, GraphQL and TypeScript
Book Description
React today is one of the most preferred choices for frontend development. Using React with TypeScript enhances development experience and offers a powerful combination to develop high performing web apps. In this book, you'll learn how to create well structured and reusable react components that are easy to read and maintain by leveraging modern web development techniques.
We will start with learning core TypeScript programming concepts before moving on to building reusable React components. You'll learn how to ensure all your components are type-safe by leveraging TypeScript's capabilities, including the latest on Project references, Tuples in rest parameters, and much more. You'll then be introduced to core features of React such as React Router, managing state with Redux and applying logic in lifecycle methods. Further on, you'll discover the latest features of React such as hooks and suspense which will enable you to create powerful function-based components. You'll get to grips with GraphQL web API using Apollo client to make your app more interactive. Finally, you'll learn how to write robust unit tests for React components using Jest.
By the end of the book, you'll be well versed with all you need to develop fully featured web apps with React and TypeScript.
What you will learn
Gain a first-hand experience of TypeScript and its productivity features
Transpile your TypeScript code into JavaScript for it to run in a browser
Learn relevant advanced types in TypeScript for creating strongly typed and reusable components.
Create stateful function-based components that handle lifecycle events using hooks
Get to know what GraphQL is and how to work with it by executing basic queries to get familiar with the syntax
Become confident in getting good unit testing coverage on your components using Jest
Who this book is for
The ideal target audience for this book are web developers who want to get started with creating modern day web apps with React and TypeScript.You are expected to have a basic understanding of JavaScript and HTML programming. No prior knowledge of TypeScript and React is needed.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 456
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Amarabha BanerjeeAcquisition Editor: Devanshi DoshiContent Development Editor: Francis CarneiroTechnical Editor: Surabhi KulkarniCopy Editor: Safis EditingProject Coordinator: Kinjal BariProofreader: Safis EditingIndexer: Rekha NairGraphics: Alishon MendonsaProduction Coordinator: Aparna Bhagat
First published: November 2018
Production reference: 1281118
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78961-025-3
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Carl Rippon has been involved in the software industry for over 20 years, developing a complex line of business applications in various sectors. He has spent the last eight years building single page applications using a wide range of JavaScript technologies, including Angular, ReactJS, and TypeScript. Carl has written over 100 blog posts on various technologies.
Ashok KumarS has been working in the mobile development domain for about six years. In his early days, he was a JavaScript and Node developer. Thanks to his strong web development skills, he has mastered web and mobile development. He is a Google-certified engineer, a speaker at global level conferences (including DroidCon Berlin and MODS), and he also runs a YouTube channel called AndroidABCD for Android developers. He is a computer science and engineering graduate who is passionate about innovation in technology. He contributes to open source heavily with a view to improving his e-karma.
He has also written books on Wear OS programming and mastering the Firebase toolchain. In his spare time, he writes articles and makes videos on programming. Ashok Kumar has also reviewed books on mobile and web development, namely Mastering JUnit 5, Android Programming for Beginners, and developing Enterprise applications using JavaScript.
Dave has had over 16 years' experience as a software engineer. After working for a number of creative agencies in London and then as a contract tech lead for a global e-commerce company, he is now tech lead at Seccl Technology, a start-up based in Bath, UK, that is building pioneering digital services for the financial industry, working with a serverless infrastructure in the cloud, and providing wonderful experiences through their web applications. He has worked with TypeScript for about five years and has seen it mature a lot over the years. Dave has worked specifically on React applications for over two years, as well on serverless code for the Seccl platform.
Pogo Kid is Dave's consultancy where he provides support for companies wanting to improve their serverless, React, and TypeScript applications. He has also reviewed a couple of book proposals for Manning on TypeScript.
He has had the privilege of bringing leadership to development teams across the world, including many household names. He is a firm believer that when systems have the correct architecture and the team has a good mix of passion and skill, users will have a wonderful experience.
Daniel Deutsch is working as a web developer in various companies. Although most of his work is structured around client-side development, he is also able to contribute to different problem areas in software development, like the backend, devops, or project management. Coming from legal fields and also studying law he aims for bringing the 2 areas together and create additional value for both industries. As his personal interest focuses on machine learning, he likes to incorporate more of those disciplines in his day to day work.
Daniel's ultimate goal is to structure a business around motivated people to create something that brings value to humanity and lasts for a long time period.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Learn React with TypeScript 3
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
TypeScript Basics
Technical requirements
Understanding the benefits of TypeScript
Catching coding errors early
Better developer experience and productivity
Using future JavaScript features
Understanding basic types
Primitive types
Type annotations
Type inference
Any
Void
Never
Enumerations
Objects
Arrays
Creating interfaces, types aliases, and classes
Interfaces
Properties
Method signatures
Optional properties and parameters
Readonly properties
Extending interfaces
Type aliases
Classes
Basic classes
Implementing interfaces
Constructors
Extending classes
Abstract classes
Access modifiers
Property setters and getters
Static
Structuring code into modules
Module formats
Exporting
Importing
Default exports
Configuring compilation
Common options
--target
--outDir
--module
--allowJS
--watch
--noImplicitAny
--noImplicitReturns
--sourceMap
--moduleResolution
tsconfig.json
Specifying files for compilation
TypeScript linting
Installing TSLint
Configuring rules
Built-in rules
Excluding files
Code formatting
Summary
Questions
Further reading
What is New in TypeScript 3
Technical requirements
Tuples
JavaScript rest and spread syntax
Open-ended tuples
Tuple function parameters
Spread expressions
Empty tuples
Optional tuple elements
The unknown type
Type checking with a type predicate
Type narrowing with a type assertion
Project references
Setting up an example
Referencing projects 
Additions to compiler options
Cross-project Go to Definition
Build mode
Default JSX properties
Summary
Questions
Further reading
Getting Started with React and TypeScript
Technical requirements
Creating a React and TypeScript project
Using create-react-app
Creating a project manually
Creating our folder structure
Creating package.json
Adding TypeScript
Creating tsconfig.json
Adding TSLint
Adding React with types
Creating a root web page
Creating a simple React component
Adding webpack
Project folders and files
Creating start and build scripts
Creating a class component
Creating a basic class component
JSX
Component props
Optional props
Default prop values
Handling class component events
Basic event handlers
The this problem
Function props
Class component states
Defining state type
Initializing the state
Changing state
Class component life cycle methods
componentDidMount 
componentWillUnmount
getDerivedStateFromProps
getSnapshotBeforeUpdate and componentDidUpdate
shouldComponentUpdate
Deprecated life cycle methods
Creating a function component
Creating a basic function component
Stateful function components
Function component life cycle hooks
Optimizing function component rendering
Summary
Questions
Further reading
Routing with React Router
Technical requirements
Installing React Router with routing types
Declaring routes
Creating navigation
Using the Link component
Using the NavLink component
Route parameters
Handling not found routes
Implementing page redirects
Simple redirect
Conditional redirect
Query parameters
Route prompts
Nested routes
Animated transitions
Lazy loading routes
Summary
Questions
Further reading
Advanced Types
Technical requirements
Union types
String literal types
String literal union types
Discriminated union pattern
Type guards
Using the typeof keyword 
Using the instanceof keyword 
Using the in keyword 
Using a user-defined type guard
Generics
Generic functions
Generic classes
Overload signatures
Lookup and mapped types
Summary
Questions
Further reading
Component Patterns
Technical requirements
Container and presentational components
Compound components
Adding reviews to a product
Creating a basic tab component
Leveraging the compound component pattern
Sharing state with React context
Render props pattern
Completing Tabs with render props
Using render prop for tab headings
Using children prop for tab content 
Higher-order components
Adding asynchronous data fetching
Implementing the withLoader HOC
Consuming the withLoader HOC
Summary
Questions
Further reading
Working with Forms
Technical requirements
Creating a form with controlled components
Adding a Contact Us page
Creating controlled inputs
Reducing boilerplate code with generic components
Creating a basic form component
Adding a basic Field component
Sharing state with React context
Implementing our new ContactUs component
Validating forms
Adding a validation rules prop to form
Tracking validation error messages
Invoking validation rules
Triggering validation rule execution from field
Rendering validation error messages
Form submission
Adding a submit button to the form
Adding a onSubmit form prop
Consuming the onSubmit form prop
Summary
Questions
Further reading
React Redux
Technical requirements
Principles and key concepts
Principles
Key concepts
Installing Redux
Creating actions
Creating state and action types
Creating actions
Creating reducers
Creating a store
Connecting our React app to the store
Adding the store Provider component
Connecting components to the store
Connecting ProductsPage to the store
Connecting ProductsPage to the loading store state
Adding product state and actions to the store
Adding basket state and actions to the store
Connecting ProductPage to the store
Creating and connecting BasketSummary to the store
Managing state with useReducer
Summary
Questions
Further reading
Interacting with RESTful APIs
Technical requirements
Writing asynchronous code
Callbacks
Callback execution
Handling callback errors
Promises
Consuming a promised-based function
Creating a promised based function
async and await
Using fetch
Getting data with fetch
Basic GET request
Getting response status
Handling errors
Creating data with fetch
Basic POST request
Request HTTP headers
Changing data with fetch
Basic PUT request
Basic PATCH request
Deleting data with fetch
Using axios with class components
Installing axios
Getting data with axios
Basic GET request
Handling errors
Request HTTP headers
Timeouts
Canceling requests
Creating data with axios
Updating data with axios
Deleting data with axios
Using axios with function components
Summary
Questions
Further reading
Interacting with GraphQL APIs
Technical requirements
GraphQL query and mutation syntax
Reading GraphQL data
Basic query
Returning nested data
Query parameters
Writing GraphQL data
Using axios as a GraphQL client
Getting a GitHub personal access token
Creating our app
Querying the GraphQL server
Using Apollo GraphQL client
Installing Apollo client
Migrating from axios to Apollo
Adding an Apollo provider
Using the query component to query GraphQL
Adding a repository search component
Implementing the search form
Implementing the search query
Rendering the search result
Implementing a mutation with Apollo
Working with cached data in Apollo
Clearing the caching using refetchQueries
Updating the cache after a Mutation
Summary
Questions
Further reading
Unit Testing with Jest
Technical requirements
Testing pure functions
Creating a basic pure function test
Understanding Jest watch options
Adding structure to unit test results
Testing components
Creating a basic component test
Improving our tests with react-testing-library
Installing react-testing-library 
Removing CSS class references from our tests
Using fireEvent for user interaction
Creating a second test for a valid form submission
Using Jest snapshot tests
Mocking dependencies
Using a mock function in Jest
Mocking Axios with axios-mock-adapter
Getting code coverage
Summary
Questions
Further reading
Answers
Chapter 1: TypeScript Basics
Chapter 2: What is New in TypeScript 3
Chapter 3:  Getting Started with React and TypeScript
Chapter 4: Routing with React Router
Chapter 5: Advanced Types
Chapter 6: Component Patterns
Chapter 7:  Working with Forms
Chapter 8: React Redux
Chapter 9: Interacting with RESTful APIs
Chapter 10: Interacting with GraphQL APIs
Chapter 11: Unit Testing with Jest
Other Books You May Enjoy
Leave a review - let other readers know what you think
React was built by Facebook in order to provide more structure to their code base and allow it to scale much better. React worked so well for Facebook that they eventually open sourced it. Today, React is one of the most popular JavaScript libraries for building frontends. It allows us to build small, isolated, and highly reusable components that can be composed together in order to create complex frontends.
TypeScript was built by Microsoft to help developers more easily build large frontend applications. It is a superset of JavaScript, bringing a rich type system to it. This type system helps developers to catch bugs early and allows tools to be created to robustly navigate and refactor code.
This book will teach you how you can use both of these technologies to create large sophisticated frontends efficiently that are easy to maintain.
This book is primarily aimed at web developers who want to create large web applications with React and TypeScript. A basic understanding of JavaScript and HTML is assumed.
Chapter 1, TypeScript Basics, introduces the TypeScript type system, covering the basic types. It moves on to cover how we can configure the incredibly flexible TypeScript compiler. Linting and code formatting are also introduced, along with their configuration.
Chapter 2, What is New in TypeScript 3, steps through the significant new features that were introduced in version 3 of TypeScript. Tuples feature heavily in this chapter, along with the closely related rest and spread syntax and how we can use these constructs with strong types. Setting up multiple related TypeScript projects efficiently is also covered, before moving on to improvements that have been made when setting default prop values in a React component.
Chapter 3, Getting Started with React and TypeScript, begins with how projects that useboth these technologies can be created. The chapter then introduces how strongly-typed React components can be built in both a class-based and functional manner. Managing state and hooking into life cycle events are also key topics in this chapter.
Chapter 4, Routing with React Router, introduces a library that can help us efficiently create an app with multiple pages. It covers how to create page links, and declare the components that should be rendered. Step by step, the chapter covers how to implement route parameters, query parameters, and nested routes. The chapter also covers how to load components from a route on demand in order to optimize performance in apps entailing lots of large pages.
Chapter 5, Advanced Types, focuses solely on TypeScript types. On this occasion, more advanced, but still very useful, types are covered, such as generic types, union types, overload signatures, and keyof and lookup types.
Chapter 6, Component Patterns, covers a number of common patterns for building React components while still maintaining strong types. Container components are stepped through first, followed by composite components. The popular render props pattern and higher-order components are also covered in this chapter.
Chapter 7, Working with Forms, covers how forms can be implemented efficiently with React and TypeScript. A generic form component is built step by step, including validation and submission.
Chapter 8, React Redux, covers how this popular library can help manage state across an app. A strongly typed Redux store is built with actions and reducers. The chapter finishes by looking at how a new React function can allow a Redux style structure within components without Redux.
Chapter 9, Interacting with RESTful APIs, begins with detailed coverage of asynchronous code. The chapter then moves on to cover how we can interact with RESTful APIs using a native JavaScript function, as well as a popular open source library.
Chapter 10,Interacting with GraphQL APIs, begins by introducing the syntax for reading and writing data. The chapter covers how to interact with a GraphQL server with an HTTP library before moving on to using a popular purpose-built library.
Chapter 11,Unit Testing with Jest, covers how to test both pure functions and React components. A popular open source library is looked at to make tests less brittle when the internals of components are refactored. Some of the great features of Jest are stepped through, such as snapshot testing, mocking, and code coverage.
Answers, Contains the answers to all the exercises present in the chapters of this book.
You need to know the basics of JavaScript, including the following:
An understanding of some of the primitive JavaScript types, such as string, number, Boolean, null, and undefined
An understanding of how to create variables and reference them, including arrays and objects
An understanding of how
to create functions and call them
An understanding of how to create conditional statements with the if and else keywords
You need to know the basics of HTML, including the following:
An understanding of basic HTML tags, such as div, ul, p, a, h1, and h2, and how to compose them together to create a web page
An understanding of how to reference a CSS class to style an HTML element
An understanding of basic CSS is also helpful, but not essential:
How to size elements and include margins and padding
How to position elements
How to color elements
You will need the following technologies installed on your computer:
Google Chrome
: This can be installed at
https://www.google.com/chrome/
.
Node.js and
npm
: These are used throughout this book. You can install them at
https://nodejs.org/en/download/
. If you already have these installed, make sure that Node.js is at least version 8.2 and that
npm
is at least version 5.2.
TypeScript
: This can be installed vianpm by entering the following command in a terminal:
npm install -g typescript
Visual Studio Code
: You'll need this to write React and TypeScript code. This can be installed from
https://code.visualstudio.com/
.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-React-with-TypeScript-3. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789610253_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Facebook has become an incredibly popular app. As its popularity grew, so did the demand for new features. React was Facebook's answer to help more people work on the codebase and deliver features quicker. React worked so well for Facebook that they eventually open sourced it. Today, React is a mature library for building component-based frontends that is extremely popular and has a massive community and ecosystem.
TypeScript is also a popular, mature library maintained by a big company – namely, Microsoft. It allows users to add strong types to their JavaScript code, helping them to be more productive, particularly in large code bases.
This book will teach you how you can use both of these awesome libraries to build robust frontends that are easy to maintain. The first couple of chapters in the book focus solely on TypeScript. You'll then start to learn about React and how you can compose robust frontends using Typescript components with strong typing.
In this chapter, we'll cover TypeScript's relationship to JavaScript and the benefits it brings. A basic understanding of JavaScript is therefore required. We'll also cover the basics of TypeScript that you'll commonly use when writing code for the browser.
You'll come to understand the need to use TypeScript for building a frontend and the sort of projects for which TypeScript really shines. You will also see how to transpile your TypeScript code into JavaScript so that it can run in a browser. Last but not least, you'll learn how you can perform additional checks on your TypeScript code to make it readable and maintainable.
By the end of the chapter, you'll be ready to start learning how you can use TypeScript for building frontends with React.
In this chapter, we'll cover the following topics:
Understanding the benefits of TypeScript
Understanding basic types
Creating interfaces, types aliases, and classes
Structuring code into modules
Configuring compilation
TypeScript linting
Code formatting
We will use the following technologies in this chapter:
TypeScript playground
: This is a website at
https://www.typescriptlang.org/play/
that allows you to play around with and understand the features in TypeScript without installing it.
Node.js and
npm
: TypeScript and React are dependent on these. You can install them at:
https://nodejs.org/en/download/
. If you already have these installed, make sure
Node.js is at least Version 8.2 and
npm
is at least Version 5.2.
TypeScript
: This can be installed via
npm
, entering the following command in a terminal:
npm install -g typescript
Visual Studio Code
: We'll need an editor to write our TypeScript code. This one can be installed from
https://code.visualstudio.com/
. Other editors that could be used can be found at
https://github.com/Microsoft/TypeScript/wiki/TypeScript-Editor-Support
.
When a JavaScript codebase grows, it can become hard to read and maintain. TypeScript is an extension of JavaScript, adding static types. The TypeScript compiler reads in TypeScript code that includes type information and produces clean, readable JavaScript with the type information transformed and removed. The compiled code can then run in our favorite browsers and Node.js.
TypeScript offers several benefits over JavaScript:
Coding errors can be caught in the development process earlier
Static types allow tools to be built that improve the developer experience and productivity
JavaScript features that aren't implemented in all the browsers yet can actually be used in an app that targets those
browsers
We'll go through these points in detail in the following sections.
Let's fix the bug in the previous section by renaming price to unitPrice. Notice how Visual Studio Code gives us IntelliSense lists unitPrice as an option because it looking at our type definition:
Here, TypeScript and Visual Studio Code are using the types to provide a better authoring experience for us. As well as IntelliSense, we are provided with code navigation features, and the safe renaming of functions and variables across multiple files. These features increase our productivity, particularly when the code base is large and there is a team of people working on it.
We touched on types in the last section. In this section, we'll go through the basic types that are commonly used in TypeScript so that we start to understand what cases we should use in each type. We'll make heavy use of the online TypeScript playground, so be sure to have that ready.
Before understanding how we declare variables and functions with types in TypeScript, let's briefly look at primitive types, which are the most basic types. Primitive types are simple values that have no properties. TypeScript shares the following primitive types with JavaScript:
string
: Represents a sequence of Unicode characters
number
: Represents both integers and floating-point numbers
boolean
: Represents a logical true or false
undefined
:
Represents a value that hasn't been initialized yet
null
: Represents no value
What if we declare a variable with no type annotation and no value? What does TypeScript infer as the type? Let's enter the following code in the TypeScript playground and find out:
let flag;
If we hover our mouse over flag, we see it has been given the any type:
So, the TypeScript compiler gives a variable with no type annotation and no immediately assigned value, the any type. The any type is specific to TypeScript; it doesn't exist in JavaScript. It is a way of opting out of type checking on a particular variable. It is commonly used for dynamic content or values from third-party libraries. However, TypeScript's increasingly powerful type system means that we need to use any less often these days.
void is another type that doesn't exist in JavaScript. It is generally used to represent a non-returning function.
Let's look at an example:
Let's enter the following function into the TypeScript playground:
function logText(text: string): void { console.log(text);}
The function simply logs some text into the console and doesn't return anything. So, we've marked the return type as void.
If we remove the return type annotation and hover over the function name,
logText
, we'll see that TypeScript has inferred the type to be
void
:
This saves us a few keystrokes while writing functions that don't return anything.
The never type represents something that would never occur and is typically used to specify unreachable areas of code. Again, this doesn't exist in JavaScript.
Time for an example:
Type the following code into the TypeScript playground:
function foreverTask(taskName: string): never { while (true) { console.log(`Doing ${taskName} over and over again ...`); }}
The function invokes an infinite loop and never returns, and so we have given it a type annotation of never. This is different to void because void means it will return, but with no value.
Let's change the
foreverTask
function to break out of the loop:
function foreverTask(taskName: string): never { while (true) { console.log(`Doing ${taskName} over and over again ...`); break; }}
The TypeScript compiler quite rightly complains:
Let's now remove the
break
statement and the
never
type annotation. If we hover over the
foreverTask
function name with our mouse, we see that TypeScript has inferred the type to be
void
, which is not what we want in this example:
The never type is useful in places where the code never returns. However, we will probably need to explicitly define the never type annotation because the TypeScript compiler isn't smart enough yet to infer that.
An interface is a contract that defines a type with a collection of property and method definitions without any implementation. Interfaces don't exist in JavaScript, so they are purely used by the TypeScript compiler to enforce the contract by type checking.
We create an interface with theinterfacekeyword, followed by its name, followed by the bits that make up the interface in curly braces:
interface Product { ...}