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

Reducing the definition of a field with a value set at construction time


It can be cumbersome to always set values from the constructor to a field. A possibility is to assign the field directly from the constructor signature into the class:

class MyClass3{
 public constructor(private p1:number, public p2:string){}
}
const myClass3 = new MyClass3(1, "2");
console.log(myClass3.p2);

By setting the visibility of the encapsulation of each parameter of the constructor, a member is created with the same type. In the preceding example, two fields are created for the class with the name and the type of the parameter. The following code is exactly the same as the previous example, which is heavier in terms of definition and assignation:

class MyClass3Same {
  private p1: number;
  public p2: string;
  public constructor(p1: number, p2: string) {
   this.p1 = p1;
   this.p2 = p2;
 }
}

const myClass3Same = new MyClass3Same (1, "2");
console.log(myClass3.p2);