Typescript Class Syntax And Constructors Complete Guide
Understanding the Core Concepts of TypeScript Class Syntax and Constructors
TypeScript Class Syntax and Constructors
1. Class Declaration
In TypeScript, a class can be declared using the class
keyword, followed by the class name. A class encapsulates data for the object. You can define properties (fields) and methods to manipulate that data.
Example:
class Car {
// Properties
make: string;
model: string;
year: number;
// Method
describe(): string {
return `${this.year} ${this.make} ${this.model}`;
}
}
2. Access Modifiers
TypeScript provides three access modifiers to control the visibility of class members: public
, private
, and protected
.
- Public: Members marked as
public
are accessible everywhere. If no modifier is specified, the member is public by default. - Private: Members marked as
private
cannot be accessed outside the containing class. - Protected: Members marked as
protected
can be accessed within the containing class and derived classes but not from outside.
Example:
class Car {
private make: string;
protected model: string;
public year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
}
3. Constructors
Constructors are special methods used to initialize objects. In TypeScript, constructors can be defined using the constructor
keyword. You can have only one constructor in a class.
Example:
class Car {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
}
4. Parameter Properties
Parameter properties let you create and initialize class properties as part of your constructor in a more concise way. They are declared by prefixing the parameter name with an access modifier.
Example:
class Car {
constructor(public make: string, public model: string, public year: number) {}
describe(): string {
return `${this.year} ${this.make} ${this.model}`;
}
}
5. Readonly Properties
Properties can be marked as readonly
to prevent modification after their initial assignment in the constructor.
Example:
class Car {
readonly make: string;
readonly model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
}
6. Inheritance
TypeScript supports class inheritance using the extends
keyword. A derived class inherits all properties and methods of the base class and can also add new members or override existing ones.
Example:
class ElectricCar extends Car {
batteryCapacity: number;
constructor(make: string, model: string, year: number, batteryCapacity: number) {
super(make, model, year);
this.batteryCapacity = batteryCapacity;
}
describe(): string {
return `${super.describe()} with a ${this.batteryCapacity} kWh battery`;
}
}
7. Abstract Classes
Abstract classes are base classes from which other classes may be derived. They cannot be instantiated directly. Abstract methods must be implemented in derived classes.
Example:
Online Code run
Step-by-Step Guide: How to Implement TypeScript Class Syntax and Constructors
Step 1: Setting Up TypeScript
Before you start, ensure you have TypeScript installed. You can install it using npm globally.
npm install -g typescript
You can also set up a local project:
mkdir typescript-class-examples
cd typescript-class-examples
npm init -y
npm install typescript --save-dev
Initialize a tsconfig.json
file for TypeScript:
npx tsc --init
Make sure your tsconfig.json
includes options for compiling and outputting JavaScript files. It should look something like this:
{
"compilerOptions": {
"target": "es6",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*"]
}
Create a src
folder where you'll put your TypeScript files:
mkdir src
Step 2: Basic Class Syntax
Let's start with a simple class that does not include a constructor.
// src/Car.ts
class Car {
make: string;
model: string;
year: number;
// Method to display car details
displayDetails(): void {
console.log(`Car: ${this.year} ${this.make} ${this.model}`);
}
}
// Create an instance of Car
let myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2020;
// Display car details
myCar.displayDetails();
Compile and run the TypeScript file:
npx tsc
node dist/Car.js
Output:
Car: 2020 Toyota Corolla
Step 3: Adding a Constructor
Now let's modify the Car
class to include a constructor to initialize properties directly when creating an instance.
// src/CarWithConstructor.ts
class Car {
make: string;
model: string;
year: number;
// Constructor to initialize properties
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
// Method to display car details
displayDetails(): void {
console.log(`Car: ${this.year} ${this.make} ${this.model}`);
}
}
// Create an instance of Car
let myCar = new Car("Toyota", "Corolla", 2020);
// Display car details
myCar.displayDetails();
Compile and run the TypeScript file:
npx tsc
node dist/CarWithConstructor.js
Output:
Car: 2020 Toyota Corolla
Step 4: Simplifying with Access Modifiers
TypeScript has access modifiers that can simplify your code. You can use public
to automatically assign constructor parameters to class properties.
// src/CarWithAccessModifiers.ts
class Car {
// Automatically assigns constructor parameters to class properties
constructor(public make: string, public model: string, public year: number) {}
// Method to display car details
displayDetails(): void {
console.log(`Car: ${this.year} ${this.make} ${this.model}`);
}
}
// Create an instance of Car
let myCar = new Car("Toyota", "Corolla", 2020);
// Display car details
myCar.displayDetails();
Compile and run the TypeScript file:
npx tsc
node dist/CarWithAccessModifiers.js
Output:
Car: 2020 Toyota Corolla
Step 5: Adding Read-Only Properties
If you want to make a property read-only, you can use the readonly
keyword. This prevents the property from being changed after the object is created.
// src/CarWithReadonly.ts
class Car {
public readonly make: string;
public model: string;
public year: number;
// Constructor to initialize properties
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
// Method to display car details
displayDetails(): void {
console.log(`Car: ${this.year} ${this.make} ${this.model}`);
}
}
// Create an instance of Car
let myCar = new Car("Toyota", "Corolla", 2020);
// Display car details
myCar.displayDetails();
// Attempt to change the make (will throw an error if uncommented)
// myCar.make = "Honda";
Compile and run the TypeScript file:
npx tsc
node dist/CarWithReadonly.js
Output:
Top 10 Interview Questions & Answers on TypeScript Class Syntax and Constructors
Top 10 Questions and Answers: TypeScript Class Syntax and Constructors
1. What is a TypeScript class?
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log(`${this.name} makes a noise.`);
}
}
2. How do you define a constructor in TypeScript?
Answer: In TypeScript, a constructor is a special method used to initialize new objects. It is defined within the class and automatically invoked when a new instance of the class is created. Here’s how you define a constructor:
class Vehicle {
make: string;
model: string;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
}
}
You can create an instance of the class Vehicle
by passing parameters to its constructor:
let myCar = new Vehicle("Toyota", "Corolla");
3. Can you explain access modifiers in TypeScript classes?
Answer: Yes, TypeScript supports three access modifiers - public
, private
, and protected
- which control the visibility and accessibility of class members:
- public: It is the default modifier. Members are accessible from anywhere.
- private: They are accessible only within the class.
- protected: They are accessible within the class and subclasses. Here’s an example:
class Person {
public name: string;
private age: number;
protected gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
4. What are readonly properties in TypeScript?
Answer: Readonly properties in TypeScript can be set only at the time of initialization in the constructor or directly in the property declaration and cannot be changed after that. You use the readonly
keyword to declare them:
class Employee {
readonly id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
5. What is a parameter property in TypeScript?
Answer: A parameter property allows you to create and initialize a class member in the constructor using a single line within the constructor parameter list. This can significantly reduce boilerplate code. You use the access modifiers directly in the constructor parameters to create parameter properties:
class Manager {
constructor(private id: number, public name: string) {}
}
6. Can constructors be overloaded in TypeScript?
Answer: TypeScript doesn't support method overloading in the traditional sense, but you can create multiple constructors by using function overloads. Here’s how:
class Point {
x: number;
y: number;
constructor(x?: number, y?: number) {
this.x = x || 0;
this.y = y || 0;
}
}
let origin = new Point();
let dist = new Point(10, 20);
7. What is a static method and property in TypeScript?
Answer: A static method or property belongs to the class rather than its instances. You use the static
keyword to define them. Static methods and properties are accessed using the class name and do not need an instance of the class to be called:
class MathUtils {
static pi: number = 3.14;
static areaOfCircle(radius: number): number {
return MathUtils.pi * Math.pow(radius, 2);
}
}
console.log(MathUtils.pi); // Outputs: 3.14
console.log(MathUtils.areaOfCircle(5)); // Outputs: 78.5
8. What is an abstract class in TypeScript?
Answer: An abstract class in TypeScript is a base class from which other classes may be derived. It cannot be instantiated directly. Abstract classes may contain implementation details for their members but can also declare abstract members that must be implemented in derived classes. They are marked with the abstract
keyword:
abstract class Shape {
abstract area(): number;
draw(): void {
console.log("Drawing a shape...");
}
}
9. What is inheritance in TypeScript?
Answer: Inheritance in TypeScript allows a class to inherit properties and methods from another class, enabling code reuse and establishing a hierarchical relationship between classes. The extends
keyword is used to create derived classes:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(): void {
console.log(`${this.name} is moving.`);
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
bark(): void {
console.log(`${this.name} barks.`);
}
}
10. What is the purpose of interfaces in TypeScript when used with classes?
Answer: Interfaces in TypeScript define a contract in your application, even though JavaScript itself doesn't have support for interfaces as understood by languages like Java. When used with classes, interfaces can be used to define a structure that a class must adhere to, ensuring that the class implements certain methods or properties. Here’s an example:
Login to post a comment.