We have come a long way in learning TypeScript since starting this series. The first tutorial gave you a brief introduction to TypeScript and suggested some IDEs that you can use for writing TypeScript. The second tutorial focused on data types, and the third tutorial discussed the basics of interfaces in TypeScript.
As you might already know, JavaScript now also has native support for classes and object-oriented programming. However, TypeScript has allowed developers to use classes in their code for a long time. This code is then compiled to JavaScript that will work across all major browsers. In this tutorial, you will learn about classes in TypeScript. They are similar to their ES6 counterparts but are stricter.
Let's start with the basics. Classes are a fundamental part of object-oriented programming. You use classes to represent any entity which has some properties and functions that may act on given properties. TypeScript gives you full control over the properties and functions that are accessible inside and outside their own containing class. Here is a very basic example of creating a Person
class.
class Person { name: string; constructor(theName: string) { this.name = theName; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } let personA = new Person("Sally"); personA.introduceSelf();
The above code creates a very simple class called Person
. This class has a property called name
and a function called introduceSelf
. The class also has a constructor, which is also basically a function. However, constructors are special because they are called every time we create a new instance of our class.
You can also pass parameters to constructors in order to initialize different properties. In our case, we are using the constructor to initialize the name of the person that we are creating using the Person
class. The introduceSelf
function is a method of the Person
class, and we are using it here to print the name of the person to the console. All these properties, methods, and the constructor of a class are collectively called class members.
You should keep in mind that the Person
class does not automatically create a person by itself. It acts more like a blueprint with all the information about the attributes a person should have once created. With that in mind, we created a new person and named her Sally. Calling the method introduceSelf
on this person will print the line "Hi, I am Sally!" to the console.
In the previous section, we created a person named Sally. Right now, it is possible to change the name of the person from Sally to Mindy anywhere in our code, as shown in the following example.
class Person { name: string; constructor(theName: string) { this.name = theName; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } let personA = new Person("Sally"); // Prints "Hi, I am Sally!" personA.introduceSelf(); personA.name = "Mindy"; // Prints "Hi, I am Mindy!" personA.introduceSelf();
You might have noticed that we were able to use both the name
property and the introduceSelf
method outside the containing class. This is because all the members of a class in TypeScript are public
by default. You can also explicitly specify that a property or method is public by adding the keyword public
before it.
Sometimes, you don't want a property or method to be accessible outside its containing class. This can be achieved by making those members private using the private
keyword. In the above code, we could make the name property private
and prevent it from being changed outside the containing class. After this change, TypeScript will show you an error saying that the name
property is private
and you can only access it inside the Person
class. The screenshot below shows the error in Visual Studio Code.
Inheritance allows you to create more complex classes starting from a base class. For example, we can use the Person
class from the previous section as a base to create a Friend
class that will have all the members of the Person
and add some members of its own. Similarly, you could also add a Family
or Teacher
class.
They will all inherit the methods and properties of the Person
while adding some methods and properties of their own to set them apart. The following example should make it clearer. I have also added the code for the Person
class here so that you can easily compare the code of both the base class and the derived class.
class Person { private name: string; constructor(theName: string) { this.name = theName; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } class Friend extends Person { yearsKnown: number; constructor(name: string, yearsKnown: number) { super(name); this.yearsKnown = yearsKnown; } timeKnown() { console.log("We have been friends for " + this.yearsKnown + " years.") } } let friendA = new Friend("Jacob", 6); // Prints: Hi, I am Jacob! friendA.introduceSelf(); // Prints: We have been friends for 6 years. friendA.timeKnown();
As you can see, you have to use the extend
keyword for the Friend
class to inherit all the members of the Person
class. It is important to remember that the constructor of a derived class must always invoke the constructor of the base class with a call to super()
before using the this
keyword.
You might have noticed that the constructor of Friend
did not need to have the same number of parameters as the base class. However, the first name parameter was passed to super()
in order to invoke the constructor of the parent, which also accepted one parameter. We did not have to redefine the introduceSelf
function inside the Friend
class because it was inherited from the Person
class.
Up to this point, we have only made the members of a class either private
or public
. While making them public allows us to access them from anywhere, making the members private limits them to their own containing class. Sometimes you might want the members of a base class to be accessible inside all the derived classes.
You can use the protected
modifier in such cases to limit the access of a member only to derived classes. You can also use the protected
keyword with the constructor of a base class. This will prevent anyone from creating an instance of that class. However, you will still be able to extend classes based on this base class.
class Person { private name: string; protected age: number; protected constructor(theName: string, theAge: number) { this.name = theName; this.age = theAge; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } class Friend extends Person { yearsKnown: number; constructor(name: string, age: number, yearsKnown: number) { super(name, age); this.yearsKnown = yearsKnown; } timeKnown() { console.log("We have been friends for " + this.yearsKnown + " years.") } friendSince() { let firstAge = this.age - this.yearsKnown; console.log(`We have been friends since I was ${firstAge} years old.`) } } let friendA = new Friend("William", 19, 8); // Prints: We have been friends since I was 11 years old. friendA.friendSince();
In the above code, you can see that we made the age
property protected
. This prevents the use of age
outside any classes derived from Person
. We have also used the protected
keyword for the constructor of the Person
class. Declaring the constructor as protected
means that we will no longer be able to directly instantiate the Person
class. The following screenshot shows an error that pops up while trying to instantiate a class with the protected
constructor.
We can use public getters and setters to access and modify the value of private members of a class in TypeScript. You can also place additional logic inside the methods to do things like validating input values. Here is an example:
class #censored# { private _name: string; private _age: number; get name() { return this._name; } set name(newName: string) { if(newName.length > 2) { this._name = newName; } else { throw new Error("Name is too short!"); } } get age() { return this._age; } set age(newAge: number) { if(newAge >= 18) { this._age = newAge; } else { throw new Error("Age must be over 18!"); } } } let person = new #censored#(); person.name = "Z"; // Error: Name is too short! person.age = 10; // Error: Age must be over 18! person.name = "Joseph"; person.age = 38; console.log(`${person.name} is ${person.age} years old.`); // Joseph is 38 years old.
In the above code, there are a few things worth noticing. The names of all private properties that we want to get and set are now prefixed with a _
like _name
. The getters and setters use the keywords get
and set
while creating a method with the same name as the property but without the prefix. We also did not need to use parentheses around name
and age
to either set or get the value of those properties using their respective methods. The correct methods were invoked automatically.
The first two assignments throw an error because we are checking inside the setters that the name is at least three characters long and the age is above or equal to 18. The getters and setters come in handy when we want to include additional checks in our code.
There are a few more things you should keep in mind. Implementing only get
but not set
will automatically make a property readonly
. The type of setter parameter is deduced from the return type of getter if it is not specified explicitly. Starting from TypeScript 4.3, you can have a set accessor that accepts different types than the ones returned by the getter.
In our previous introductory tutorial on interfaces in TypeScript, we learned that interfaces are basically used to specify the structure of different objects that we will use in our code. Now, we will learn how we can implement classes based on some previously declared interfaces.
interface IPoint { x: number, y: number, position(x: number, y: number): void } interface IRectangle extends IPoint { width: number, length: number, area(width: number, length: number): number } class Point implements IPoint { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } position(): void { console.log(`The point is at (${this.x}, ${this.y}).`); } } class Rectangle implements IRectangle { width: number; length: number; x: number; y: number; constructor(x: number, y: number, width: number, length: number) { this.x = x; this.y = y; this.width = width; this.length = length; } area(): number { return this.width*this.length; } position(): void { console.log(`The rectangle is at (${this.x}, ${this.y}).`); } } let myPoint = new Point(10, 20); let myRect = new Rectangle(0, 0, 20, 30); myPoint.position(); myRect.position(); console.log(myRect.area());
We create an IPoint
interface to store coordinates and then extend it to create an IRectangle
interface, as we did in the previous tutorial. One additional change here is that we also added a function declaration to the interface.
The Rectangle
class implements IRectangle
, which means that it will have these four properties and two methods to output its position and display its area.
In this tutorial, I have tried to cover the basics of classes in TypeScript. We began the tutorial by creating a very basic Person
class that printed the name of the person to the console. After that, you learned about the private
keyword, which can be used to prevent the members of a class from being accessed at any arbitrary point in the program.
Finally, you learned how to extend different classes in your code using a base class with inheritance. You can learn a lot more about classes in the official documentation.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
10 Best WordPress Twitter Widgets
1 /20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/20 Best WordPress Calendar Plugins and Widgets
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Short Course: Better Angular App Architecture With Modules
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/10 Best WordPress Facebook Widgets
13Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
/12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
/Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
/Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Learn Computer Science With JavaScript: Part 1, The Basics
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
/Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/9 More Popular HTML5 Projects for You to Use and Study
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…