TypeScript Class
A TypeScript class defines the properties and methods shared by objects of a particular type. Classes support familiar object-oriented features such as constructors, inheritance, access modifiers, abstract members, static members, and interfaces.
This tutorial explains TypeScript class syntax, constructors, properties, methods, object creation, access modifiers, inheritance, abstract classes, and class types through practical examples.
TypeScript Class Syntax
Use the class keyword followed by the class name and a class body. The body can contain property declarations, a constructor, methods, accessors, and static members.
class className{
// variables
// constructors
// functions
}
- class is the keyword used to declare a class.
- className identifies the class and is conventionally written in PascalCase.
- Variables, commonly called properties or fields, store the state of each object.
- The constructor initializes a new object when the class is instantiated.
- Functions declared in a class are called methods and define object behavior.
Simple TypeScript Class Example
The following Student class contains two properties, a constructor, and a method. The constructor receives a roll number and name, while the method displays the stored information.
student.ts
class Student{
// variables
rollnumber:number
name:string
// constructors
constructor(rollnumber:number, name:string){
this.rollnumber = rollnumber
this.name = name
}
// functions
displayInformation():void{
console.log("Name : "+this.name+", Roll Number : "+this.rollnumber)
}
}
Compile the TypeScript file with the TypeScript compiler:
$ tsc student.ts
The generated JavaScript depends on the target selected in tsconfig.json. An older JavaScript target can produce code similar to the following output.
student.js
var Student = /** @class */ (function () {
// constructors
function Student(rollnumber, name) {
this.rollnumber = rollnumber;
this.name = name;
}
// functions
Student.prototype.displayInformation = function () {
console.log("Name : " + this.name + ", Roll Number : " + this.rollnumber);
};
return Student;
}());
The TypeScript type annotations are used during type checking and are not normally present in the emitted JavaScript. Class behavior remains available in the generated code.
Declaring TypeScript Class Properties
Declare a class property by writing its name followed by a colon and its type. Do not place let, const, or var before a property declaration inside the class body.
variableName: variableType
Student Class Property Declarations
rollnumber: number
name: string
A property can also receive an initializer. The initializer is evaluated when an object is created.
class Course {
title: string = "TypeScript Basics";
enrolled: boolean = false;
}
Defining a TypeScript Class Constructor
A constructor initializes an object when the new expression creates it. A class can contain only one constructor implementation, although TypeScript allows constructor overload signatures above that implementation.
Write the constructor keyword, place its parameters in parentheses, and add the initialization statements inside braces.
constructor(variable1:variableType, variable2:variableType){
// load class variables with the parameter values
}
When a constructor parameter and class property have the same name, use this to refer to the property of the current object.
Student Class Constructor Example
constructor(rollnumber:number, name:string){
this.rollnumber = rollnumber
this.name = name
}
Here, this.rollnumber and this.name refer to properties of the object being initialized. The unqualified names refer to the constructor parameters.
TypeScript Constructor Parameter Properties
TypeScript can declare and initialize a property directly from a constructor parameter. Add an access modifier such as public, private, or protected, or use readonly, before the parameter name.
class Product {
constructor(
public name: string,
public price: number,
readonly sku: string
) {}
}
const product = new Product("Keyboard", 2500, "KB-101");
console.log(product.name);
console.log(product.sku);
This compact form creates the properties and assigns the corresponding constructor arguments. Because sku is readonly, it cannot be reassigned after initialization.
Declaring Methods in a TypeScript Class
A class method is declared with a method name, parameter list, optional return type, and body. Methods can read or update object properties through this.
Student Class Method Example
displayInformation():void{
console.log("Name : "+this.name+", Roll Number : "+this.rollnumber)
}
displayInformation accepts no parameters and has a void return type because it does not return a value. It writes a formatted string to the console.
Creating Objects from a TypeScript Class
An object is an instance created from a class. Each instance has its own instance-property values, while its methods provide the behavior defined by the class.
Syntax for Instantiating a TypeScript Class
Use the new operator to call the class constructor and create an object:
var object1 = new ClassName(arguments)
- object1 stores the reference to the newly created object.
- new creates an instance and invokes the class constructor.
- ClassName identifies the class to instantiate.
- arguments must satisfy the constructor parameter types.
The existing syntax is valid, but const is generally appropriate when the variable will continue to refer to the same object. It prevents reassignment of the variable; it does not make all properties of the object immutable.
Creating Student Class Instances
The following statements create two objects from the Student class and pass different values to its constructor.
var student1 = new Student(2, "Rohit")
var student2 = new Student(4, "Kohli")
Accessing TypeScript Object Properties and Methods
Use the dot operator to access a public property or call a public method. Members marked private or protected have additional access restrictions explained later in this tutorial.
The complete example creates two students, reads their properties, and calls their methods.
example.ts
class Student{
// variables
rollnumber:number
name:string
// constructors
constructor(rollnumber:number, name:string){
this.rollnumber = rollnumber
this.name = name
}
// functions
displayInformation():void{
console.log("Name : "+this.name+", Roll Number : "+this.rollnumber)
}
}
var student1 = new Student(2, "Rohit")
var student2 = new Student(4, "Kohli")
// accessing variables
console.log(student1.name)
console.log(student2.rollnumber)
// calling functions
student1.displayInformation()
student2.displayInformation()
The first two console.log calls read individual properties. The final two statements invoke displayInformation() on different instances.
Rohit
4
Name : Rohit, Roll Number : 2
Name : Kohli, Roll Number : 4
When compiled for an older JavaScript target, the generated code can look like this:
example.js
var Student = /** @class */ (function () {
// constructors
function Student(rollnumber, name) {
this.rollnumber = rollnumber;
this.name = name;
}
// functions
Student.prototype.displayInformation = function () {
console.log("Name : " + this.name + ", Roll Number : " + this.rollnumber);
};
return Student;
}());
var student1 = new Student(2, "Rohit");
var student2 = new Student(4, "Kohli");
// accessing variables
console.log(student1.name);
console.log(student2.rollnumber);
// calling functions
student1.displayInformation();
student2.displayInformation();
Public, Private, and Protected Class Members
TypeScript access modifiers control where a class member can be referenced during type checking.
| Modifier | Where the member can be accessed |
|---|---|
public | Inside the class, in derived classes, and through class objects. This is the default. |
private | Inside the class that declares the member. |
protected | Inside the declaring class and its derived classes. |
readonly | The property can be read normally but assigned only at its declaration or during construction. |
class BankAccount {
public owner: string;
private balance: number;
protected accountType: string;
constructor(owner: string, openingBalance: number) {
this.owner = owner;
this.balance = openingBalance;
this.accountType = "Savings";
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount("Maya", 5000);
console.log(account.owner);
console.log(account.getBalance());
Access modifiers mainly provide compile-time checks. JavaScript private fields written with a # prefix have runtime-enforced privacy and are different from TypeScript’s private modifier.
Getters and Setters in TypeScript Classes
Accessors expose property-like syntax while keeping validation or calculation logic inside the class. Use get to read a value and set to handle an assignment.
class Temperature {
private _celsius: number = 0;
get celsius(): number {
return this._celsius;
}
set celsius(value: number) {
if (value < -273.15) {
throw new RangeError("Temperature is below absolute zero");
}
this._celsius = value;
}
}
const reading = new Temperature();
reading.celsius = 24;
console.log(reading.celsius);
Static Properties and Methods in TypeScript
A static member belongs to the class itself rather than to an individual instance. Access it through the class name.
class IdGenerator {
private static nextId: number = 1;
static createId(): number {
return this.nextId++;
}
}
console.log(IdGenerator.createId());
console.log(IdGenerator.createId());
1
2
TypeScript Class Inheritance with extends and super
A derived class uses extends to inherit accessible members from a base class. If the derived class declares a constructor, it must call super() before accessing this.
class Person {
constructor(public name: string) {}
describe(): string {
return `Person: ${this.name}`;
}
}
class Employee extends Person {
constructor(name: string, public department: string) {
super(name);
}
describe(): string {
return `${this.name} works in ${this.department}`;
}
}
const employee = new Employee("Anita", "Engineering");
console.log(employee.describe());
The Employee class inherits name and overrides describe(). The super(name) call runs the base-class constructor.
Implementing an Interface with a TypeScript Class
The implements clause checks that a class provides the instance members required by an interface. It does not copy an implementation into the class.
interface Printable {
print(): string;
}
class Invoice implements Printable {
constructor(public invoiceNumber: string) {}
print(): string {
return `Invoice ${this.invoiceNumber}`;
}
}
const invoice = new Invoice("INV-104");
console.log(invoice.print());
TypeScript Abstract Class Example
An abstract class can define shared implementation while requiring derived classes to implement selected members. It cannot be instantiated directly.
abstract class Shape {
abstract area(): number;
describe(): string {
return `Area: ${this.area()}`;
}
}
class Rectangle extends Shape {
constructor(
private width: number,
private height: number
) {
super();
}
area(): number {
return this.width * this.height;
}
}
const rectangle = new Rectangle(6, 4);
console.log(rectangle.describe());
Area: 24
Using a TypeScript Class as a Type
A class declaration creates a runtime constructor value and an instance type. The class name can therefore be used as a type annotation for variables, parameters, and return values.
class User {
constructor(public name: string) {}
}
function displayUser(user: User): string {
return user.name;
}
const currentUser: User = new User("Arun");
console.log(displayUser(currentUser));
TypeScript uses structural typing for most class compatibility checks. An object with the required public instance structure may be compatible even if it was not created by that class. Private and protected members affect this compatibility.
Generic TypeScript Class Example
A generic class accepts a type parameter so the same class logic can work with different value types while retaining type safety.
class Box<T> {
constructor(private value: T) {}
getValue(): T {
return this.value;
}
}
const numberBox = new Box<number>(25);
const textBox = new Box<string>("TypeScript");
console.log(numberBox.getValue());
console.log(textBox.getValue());
Class Property Initialization under strictPropertyInitialization
When strictPropertyInitialization is enabled, an instance property must have an initializer, be assigned in the constructor, or be explicitly declared in another acceptable form. This check helps detect properties that could otherwise remain undefined.
- Assign the property at its declaration when a sensible default exists.
- Assign it on every constructor path when callers must provide the value.
- Mark it optional with
?when the property may legitimately be absent. - Use the definite-assignment assertion
!only when initialization occurs through code the compiler cannot analyze, such as a framework lifecycle method.
class Profile {
username: string;
bio?: string;
createdAt: Date = new Date();
avatarElement!: HTMLImageElement;
constructor(username: string) {
this.username = username;
}
}
TypeScript Class Implementation Checklist
- Confirm that every class property has an explicit type or a clearly inferred initializer.
- Check that constructor arguments initialize all required instance properties.
- Keep implementation details
privateorprotectedwhen callers should not access them directly. - Use
readonlyfor references that must not be reassigned after construction. - Call
super()before usingthisin a derived-class constructor. - Use
staticonly for data or behavior that belongs to the class rather than an individual object. - Verify that every class with an
implementsclause supplies all required interface members. - Compile with the project’s actual
tsconfig.jsonsettings because strictness and emitted JavaScript depend on compiler configuration.
Frequently Asked Questions about TypeScript Classes
What is a class in TypeScript?
A class is a declaration that describes how to construct objects and which properties and methods their instances provide. TypeScript adds static type checking and features such as access modifiers and abstract members to JavaScript class syntax.
How do you create an object from a TypeScript class?
Use the new operator followed by the class name and constructor arguments, for example, const user = new User("Arun").
Can a TypeScript class have multiple constructors?
A class can have several constructor overload signatures but only one constructor implementation. That implementation must handle all supported argument combinations.
What is the difference between an interface and an abstract class in TypeScript?
An interface describes a type contract and does not provide runtime implementation. An abstract class can contain fields, constructors, and implemented methods in addition to abstract members. A class can implement multiple interfaces but can extend only one base class.
Are TypeScript private properties private at runtime?
The private modifier is primarily enforced by the TypeScript type checker. For JavaScript runtime privacy, use supported #privateField syntax where appropriate.
Summary of TypeScript Class Syntax and Features
A TypeScript class groups object properties and methods under a reusable definition. Constructors initialize instances, access modifiers control member visibility during type checking, and features such as inheritance, interfaces, abstract classes, static members, accessors, and generics support larger object models. For additional language details, refer to the official TypeScript classes documentation.
Continue with the TypeScript Tutorial for related TypeScript concepts and examples.
TutorialKart.com