Step 5 – Object types and interfaces in TypeScript

In TypeScript, an object type represents a set of properties and their corresponding types. An interface is a way to define an object type in TypeScript.

Defining an Interface

To define an interface, use the interface keyword followed by the interface name and the list of properties and their types enclosed in curly braces:

interface Person {
  name: string;
  age: number;
  email?: string; // optional property
}

In this example, we define an interface Person that has three properties: name of type string, age of type number, and email of type string, which is optional.

Implementing an Interface

To implement an interface, use the implements keyword followed by the interface name:

class Employee implements Person {
  name: string;
  age: number;
  email?: string;

  constructor(name: string, age: number, email?: string) {
    this.name = name;
    this.age = age;
    this.email = email;
  }
}

In this example, we define a class Employee that implements the Person interface. We also define a constructor that sets the properties of the Employee object.

Object Types

An object type is a type that represents an object with a set of properties and their corresponding types. You can define an object type using the same syntax as an interface:

type Person = {
  name: string;
  age: number;
  email?: string;
}

In this example, we define an object type Person using the type keyword. The syntax is the same as for defining an interface.

Readonly Properties

You can make a property readonly by using the readonly keyword:

interface Person {
  readonly name: string;
  age: number;
}

In this example, the name property is readonly, meaning that it can’t be changed once it’s been set.

Extending Interfaces

You can extend an interface by using the extends keyword:

interface Person {
  name: string;
  age: number;
}

interface Employee extends Person {
  id: number;
  department: string;
}

In this example, we define an interface Employee that extends the Person interface. The Employee interface has two additional properties: id of type number and department of type string.

Summary

In this overview, we looked at object types and interfaces in TypeScript. We saw how to define an interface, implement an interface, define an object type, make properties readonly, extend an interface, and more.

Diagram:

+—————-+
| Person |
+——————+
| name: string |
| age: number |
| email?: string |
+——————+
^
|
+——–+——–+
| |
| Employee |
| |
+————————-+
| name: string |
| age: number |
| email?: string |
| id: number |
| department: string |
+————————–+

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.