Book Image

TypeScript 3.0 Quick Start Guide

By : Patrick Desjardins
Book Image

TypeScript 3.0 Quick Start Guide

By: Patrick Desjardins

Overview of this book

<p>TypeScript is designed for the development of large applications and can be used to develop JavaScript applications for both client-side and server-side execution. This book is the ideal introduction to TypeScript, covering both the basics and the techniques you need to build your own applications.</p> <p>We start by setting up the environment and learning about the build tools that support TypeScript. Then we look at scoping of a variable, and the difference between a undefined variable and a null variable. You will then see the difference between an object, an Object, an object literal, and an object built with a constructor, crucial concepts in understanding TypeScript.</p> <p>You will learn how to make your code more generic to increase the reusability of your classes, functions, and structures, and to reduce the burden of duplicating code. We look at creating definition files to transform the actual JavaScript code to be compatible with TypeScript.</p> <p>By the end of the book, you will have worked with everything you need to develop stunning applications using TypeScript.</p>
Table of Contents (14 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Free Chapter
1
Getting Started with TypeScript
Index

Default generic


The more you work with generic, the more you may find that for a particular case in your system you are using always the same type. It could almost not be generic but be of a specific type. In that case, it is interesting to use a default type for your generic. A default generic type allows avoids having to specify a type. A default generic is also known as an optional type.

TypeScript uses the type specified in the generic signature after the equals sign:

interface BaseType<T = string> {
 id: T;
}
let entity1: BaseType;
let entity2: BaseType<string>;
let entity3: BaseType<number>;

Three variables are declared. The first and second ones are exactly the same: they expect an object with an id of a string type. The last is a number. The reason the first and second are exactly the same is that the first declaration relies on the default type. The default type is specified in the generic definition of the interface after the name of the type, T. The use of the equals...