SYS-CON MEDIA Authors: Pat Romanski, Gary Arora, Zakia Bouachraoui, Yeshim Deniz, Liz McMillan

Blog Feed Post

Getting started with TypeScript classes

This blog is a part of my TypeScript series, and the previous ones are:

1. Why program in TypeScript
2. Structural vs nominal typing

In the next several blogs, I’ll focus on object-oriented features of Typescript – classes and interfaces. Let’s start with classes.

First of all, let me remind you that starting from the ECMAScript 2015 spec (a.k.a. ES6), JavaScript supports classes. Being a superset of JavaScript, TypeScript supports all features from JavaScript classes and adds some extras.

For example, JavaScript doesn’t offer syntax for declaring class properties, but TypeScript does. In the screenshot below on the left, you can see how I declared and instantiated the class Person that has three properties. The right side shows the ES6 version of this code produced by the TypeScript compiler:

https://yakovfain.files.wordpress.com/2018/09/u1_person_class.png?w=1520... 1520w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class.png?w=150&... 150w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class.png?w=300&... 300w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class.png?w=768&... 768w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class.png?w=1024... 1024w" sizes="(max-width: 760px) 100vw, 760px" />

As you see, there are no properties in the JavaScript version of the class Person. Also, since the class Person didn’t declare a constructor, we had to initialize its properties after instantiating. A constructor is a special function that’s executed only once when the instance of a class is created.

Declaring a constructor with three arguments would allow you to instantiate the class Person and initialize its properties in one line. In TypeScript, you can provide type annotation for constructor’s arguments, but there’s more.

TypeScript offers access level qualifiers public, private, and protected (I’ll cover these in the future blog), and if you use any of them with the constructor arguments, the TypeScript will generate the code for adding these properties in a JavaScript object as in the following screenshot:

https://yakovfain.files.wordpress.com/2018/09/u1_person_class_constructo... 1520w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class_constructo... 150w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class_constructo... 300w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class_constructo... 768w, https://yakovfain.files.wordpress.com/2018/09/u1_person_class_constructo... 1024w" sizes="(max-width: 760px) 100vw, 760px" />

Now the code of the TypeScript class (on the left) is more concise and the generated JavaScript code creates three properties in the constructor. We’d like to bring your attention to line 6 in the above screenshot on the left. We declared the constant without specifying its type, but we could have re-written this line explicitly specifying the type of p as follows:

const p: Person = new Person("John", "Smith", 25);

This illustrates an unnecessary use of an explicit type annotation. Since you declare a constant and immediately initialize it with an object of a known type (i.e. Person), the TypeScript type checker can easily infer and assign the type to the constant p. The generated JavaScript code will look the same with or without specifying the type of p. You can try it in the TypeScript playground by following this link.

Regardless if a class has a constructor or it doesn’t, classes allow you to declare custom types that didn’t exist in TypeScript before.

NOTE: We use the public access level with each constructor argument in the TypeScript class, which simply means that the generated corresponding properties can be accessed from any code located both inside and outside of the class.

When you declare the properties of a class, you can also mark them as readonly. Such properties can be initialized either at the declaration point or in the class constructor, and their values can’t be changed afterwards. The readonly qualifier is similar to the const keyword, but the latter can’t be used with class properties.

Getting familiar with class inheritance

In real life, every person inherits some features from his or her parents. Similarly, in the TypeScript world, you can create a new class, based on the existing one. For example, you can create a class Person with some properties and then the class Employee that will _inherit_ all the properties of Person and declare some additional ones.

Inheritance is one of the main features of any object-oriented language. TypeScript has the keyword extends to declare that one class is inherited from the other.

The line 7 in the following screenshot shows how to declare an Employee class that extends the class Person and declares an additional property department. In line 11, we create an instance of the class Employee.

https://yakovfain.files.wordpress.com/2018/09/class_extends.png?w=1520&h... 1520w, https://yakovfain.files.wordpress.com/2018/09/class_extends.png?w=150&h=56 150w, https://yakovfain.files.wordpress.com/2018/09/class_extends.png?w=300&h=112 300w, https://yakovfain.files.wordpress.com/2018/09/class_extends.png?w=768&h=287 768w, https://yakovfain.files.wordpress.com/2018/09/class_extends.png?w=1024&h... 1024w" sizes="(max-width: 760px) 100vw, 760px" />

This screenshot was taken from the playground at typscriptlang.org after we entered empl. followed by CTRL-Space on line 13. The TypeScript’s static analyzer recognizes that the type Employee is inherited from Person so it suggests the properties defined in both classes Person and Employee.

In our example, the class Employee is a subclass of Person. Accordingly, the class Person is a superclass of Employee. You can also say that the class Person is an ancestor and Employee is a descendant of Person.

NOTE: Under the hood, JavaScript supports prototypal _object-based_ inheritance, where one object can assign another object as its prototype, and this happens during the runtime. During transpiling to JavaScript, the generated code uses the syntax of the prototypal inheritance as seen in the above screenshot on the right.

In addition to properties, a class can include _methods_ – this is how we call functions declared inside the classes. And if a method(s) is declared in a superclass, it will be inherited by the subclass unless the method was declared with the access qualified private which we’ll discuss a bit later.

The next version of the class Person is shown in the screenshot below, and it includes the method sayHello(). As you can see in line 17, TypeScript included this method in its typeahead help.

https://yakovfain.files.wordpress.com/2018/09/class_extends_method.png?w... 150w, https://yakovfain.files.wordpress.com/2018/09/class_extends_method.png?w... 300w, https://yakovfain.files.wordpress.com/2018/09/class_extends_method.png?w... 768w, https://yakovfain.files.wordpress.com/2018/09/class_extends_method.png 880w" sizes="(max-width: 760px) 100vw, 760px" />

You may be wondering, “Is there any way to control which properties and methods of a superclass are accessible from the subclass?”
Actually, a more general question would be “Is there any way to control which properties and methods of a class are accessible from other scripts?” The answer is yes – this is what the private, protected, and public keywords are for, and I’ll cover them in the next blog. Stay tuned…

Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Latest Stories
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
On-premise or off, you have powerful tools available to maximize the value of your infrastructure and you demand more visibility and operational control. Fortunately, data center management tools keep a vigil on memory contestation, power, thermal consumption, server health, and utilization, allowing better control no matter your cloud's shape. In this session, learn how Intel software tools enable real-time monitoring and precise management to lower operational costs and optimize infrastructure...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical Infrastructure as a Service cloud provider but it's been designed around data privacy," explained Julian Box, CEO and co-founder of Calligo, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Isomorphic Software is the global leader in high-end, web-based business applications. We develop, market, and support the SmartClient & Smart GWT HTML5/Ajax platform, combining the productivity and performance of traditional desktop software with the simplicity and reach of the open web. With staff in 10 timezones, Isomorphic provides a global network of services related to our technology, with offerings ranging from turnkey application development to SLA-backed enterprise support. Leadin...
While a hybrid cloud can ease that transition, designing and deploy that hybrid cloud still offers challenges for organizations concerned about lack of available cloud skillsets within their organization. Managed service providers offer a unique opportunity to fill those gaps and get organizations of all sizes on a hybrid cloud that meets their comfort level, while delivering enhanced benefits for cost, efficiency, agility, mobility, and elasticity.
DevOps has long focused on reinventing the SDLC (e.g. with CI/CD, ARA, pipeline automation etc.), while reinvention of IT Ops has lagged. However, new approaches like Site Reliability Engineering, Observability, Containerization, Operations Analytics, and ML/AI are driving a resurgence of IT Ops. In this session our expert panel will focus on how these new ideas are [putting the Ops back in DevOps orbringing modern IT Ops to DevOps].
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Enterprises are striving to become digital businesses for differentiated innovation and customer-centricity. Traditionally, they focused on digitizing processes and paper workflow. To be a disruptor and compete against new players, they need to gain insight into business data and innovate at scale. Cloud and cognitive technologies can help them leverage hidden data in SAP/ERP systems to fuel their businesses to accelerate digital transformation success.
Most organizations are awash today in data and IT systems, yet they're still struggling mightily to use these invaluable assets to meet the rising demand for new digital solutions and customer experiences that drive innovation and growth. What's lacking are potent and effective ways to rapidly combine together on-premises IT and the numerous commercial clouds that the average organization has in place today into effective new business solutions.
Concerns about security, downtime and latency, budgets, and general unfamiliarity with cloud technologies continue to create hesitation for many organizations that truly need to be developing a cloud strategy. Hybrid cloud solutions are helping to elevate those concerns by enabling the combination or orchestration of two or more platforms, including on-premise infrastructure, private clouds and/or third-party, public cloud services. This gives organizations more comfort to begin their digital tr...
Keeping an application running at scale can be a daunting task. When do you need to add more capacity? Larger databases? Additional servers? These questions get harder as the complexity of your application grows. Microservice based architectures and cloud-based dynamic infrastructures are technologies that help you keep your application running with high availability, even during times of extreme scaling. But real cloud success, at scale, requires much more than a basic lift-and-shift migrati...
David Friend is the co-founder and CEO of Wasabi, the hot cloud storage company that delivers fast, low-cost, and reliable cloud storage. Prior to Wasabi, David co-founded Carbonite, one of the world's leading cloud backup companies. A successful tech entrepreneur for more than 30 years, David got his start at ARP Instruments, a manufacturer of synthesizers for rock bands, where he worked with leading musicians of the day like Stevie Wonder, Pete Townsend of The Who, and Led Zeppelin. David has ...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Addteq is a leader in providing business solutions to Enterprise clients. Addteq has been in the business for more than 10 years. Through the use of DevOps automation, Addteq strives on creating innovative solutions to solve business processes. Clients depend on Addteq to modernize the software delivery process by providing Atlassian solutions, create custom add-ons, conduct training, offer hosting, perform DevOps services, and provide overall support services.