Reader small image

You're reading from  Mastering TypeScript - Fourth Edition

Product typeBook
Published inApr 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781800564732
Edition4th Edition
Languages
Right arrow
Author (1)
Nathan Rozentals
Nathan Rozentals
author image
Nathan Rozentals

Nathan Rozentals has been writing commercial software for over 30 years, in C, C++, Java and C#. He picked up TypeScript within a week after its initial release in October 2012 and realized how much TypeScript could help when writing JavaScript. He was one of the first people to start blogging about TypeScript, discussing early frameworks such as Backbone, Marionette, ExtJS and AngularJs. He knew he'd hit the mark when Microsoft staff started to reference his blog posts in their CodePlex discussion forums. Nathan's TypeScript solutions now control User Interfaces in IoT devices, run as stand-alone applications for Point-of-Sale solutions, provide complex application configuration web sites, and are used for mission-critical server APIs.
Read more about Nathan Rozentals

Right arrow

Interfaces, Classes, Inheritance, and Modules

We have already seen a variety of language enhancements that TypeScript brings to modern JavaScript development. This includes the primitive types, like string, number, boolean, undefined, and never, as well as features brought in from multiple ECMAScript standards, like let, const, and optional chaining. TypeScript, therefore, allows us to use these enhanced language features from future JavaScript standards in our code right now, and it takes care of generating the correct JavaScript based on our runtime target.

The ECMAScript standard published in 2015, known as ES6, introduced the concept of classes and inheritance. JavaScript programmers, however, have been able to create classes and use object-oriented programming techniques for many years, by using what is known as the closure design pattern and the prototype design pattern. The creation of JavaScript objects through closures, however, has been more by convention than being...

Interfaces

In Chapter 1, Up and Running Quickly, we discussed how TypeScript uses duck typing to assess if two objects are compatible. These typing rules govern whether an object can be assigned to another and compares the properties of one object to the other.

Interfaces provide us with a mechanism to define what properties an object must implement and is, therefore, a way for us to define a custom type. By defining an interface, we are describing the properties and functions that an object is expected to have in order to be used by our code.

To illustrate these concepts, consider the following code:

interface IIdName {
    id: number;
    name: string;
}

Here, we have used the interface keyword to define a TypeScript interface named IIdName. This interface describes an object that has an id property of type number, and a name property of type string. Once we have defined an interface, we can use it in the same way as a primitive type, as follows:

let idObject...

Classes

A class is the definition of an object, what data it holds, and what operations it can perform. Classes and interfaces form the cornerstone of object-oriented programming. Let's take a look at a simple class definition, as follows:

class SimpleClass {
    id: number;
    print(): void {
        console.log(`SimpleClass.print() called.`);
    }
}

Here, we have defined a class, using the class keyword, which is named SimpleClass, and has an id property of type number, and a print function, which just logs a message to the console. Notice anything wrong with this code? Well, the compiler will generate an error message as follows:

error TS2564: Property 'id' has no initializer and is not definitely assigned in the constructor

What this error is indicating is that if we create an instance of this class, then the newly created class will not have the id property initialized, and it will therefore be undefined. If our code is expecting the id property...

Inheritance

Inheritance is another paradigm that is one of the cornerstones of object-oriented programming. Inheritance allows us to create an object based on another object, thereby inheriting all of its characteristics, including properties and functions. In TypeScript, inheritance can be used by classes and interfaces. In this section of the chapter, we will take a closer look at inheritance, and what it means for both classes and interfaces.

When discussing inheritance, it is important to clearly distinguish between the class that forms the basis of the inheritance structure, and the class that is doing all of the inheriting. We will use the term "base class," or "base interface," to denote the class or interface that forms the base of the inheritance structure, and the term "derived class," or "derived interface," to denote the class or interface that is doing the inheriting.

TypeScript uses the keyword extends to implement inheritance...

Modules

Modularization is a popular technique used in programming languages that allows programs to be built from a series of smaller libraries, or modules. This technique is also applied to object-oriented code bases, where each class is typically housed in its own file. When referencing classes that exist in another source file, we need a mechanism for the TypeScript compiler, as well as the JavaScript runtime, to be able to locate the class that we are referencing. This is where modules are used.

TypeScript has adopted the module syntax that is part of ES2015. This means that we can use this syntax when working with modules, and the compiler will generate the relevant JavaScript to support modules based on the target JavaScript version we have selected. There is no change in syntax, and there is no change in our code in order to support earlier versions of the JavaScript runtime.

In this section of the chapter, we will walk through the module syntax, and discuss how to...

Summary

We have covered a lot of ground in this chapter. We started with a discussion on interfaces, and how they allow us to define custom types that can be used to better describe objects with their designated properties and sub-properties. We then moved on to discuss classes, and how to use the various TypeScript language features that are specially designed with classes in mind. This discussion included class constructors, class modifiers, readonly properties, get and set functions, and static properties and methods. We then discussed the ins and outs of class and interface inheritance. We took a look at the super keyword, and how it can be used within class constructors as well as class methods in a class hierarchy. We then discussed abstract classes, abstract methods, the protected access modifier, and instanceof. In the final section of this chapter, we discussed modules, and how breaking up a large project into multiple smaller files can aid with code structure. We showed...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering TypeScript - Fourth Edition
Published in: Apr 2021Publisher: PacktISBN-13: 9781800564732
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Nathan Rozentals

Nathan Rozentals has been writing commercial software for over 30 years, in C, C++, Java and C#. He picked up TypeScript within a week after its initial release in October 2012 and realized how much TypeScript could help when writing JavaScript. He was one of the first people to start blogging about TypeScript, discussing early frameworks such as Backbone, Marionette, ExtJS and AngularJs. He knew he'd hit the mark when Microsoft staff started to reference his blog posts in their CodePlex discussion forums. Nathan's TypeScript solutions now control User Interfaces in IoT devices, run as stand-alone applications for Point-of-Sale solutions, provide complex application configuration web sites, and are used for mission-critical server APIs.
Read more about Nathan Rozentals