Post

Typescript Pt. 4 - Interfaces

Interfaces in TypeScript are a way to define the shape of an object. They are similar to type aliases, but with some differences.

Creating an interface

1
2
3
4
interface Person {
  name: string;
  age: number;
}

Creating an interface with optional properties

1
2
3
4
interface Person {
  name: string;
  age?: number;
}

In the above example, the age property is optional.

Creating an interface with readonly properties

1
2
3
4
interface Person {
  readonly name: string;
  readonly age: number;
}

In the above example, the name and age properties are readonly. This means that they cannot be changed after they are created.

Creating an interface with methods

1
2
3
4
5
interface Person {
  name: string;
  age: number;
  sayHello(): void;
}

In the above example, the sayHello method takes no arguments and returns nothing.

Creating an interface with a method that takes arguments

1
2
3
4
5
interface Person {
  name: string;
  age: number;
  sayHello(name: string): void;
}

In the above example, the sayHello method takes a name argument and returns nothing.

Using an interface

1
2
3
4
let person: Person = {
  name: "John",
  age: 30,
};
  • using an interface that has a method
1
2
3
4
5
6
7
let person: Person = {
  name: "John",
  age: 30,
  sayHello(name: string): void {
    console.log(`Hello, ${name}!`);
  },
};

Extending an interface

In TypeScript, you can extend an interface by using the extends keyword. This allows you to add new properties to an existing interface.

1
2
3
4
5
6
7
8
interface Person {
  name: string;
  age: number;
}

interface Employee extends Person {
  salary: number;
}

Reopening an interface

In TypeScript, you can reopen an interface by using the declare keyword. This allows you to add new properties to an existing interface.

1
2
3
4
5
6
7
8
interface Person {
  name: string;
  age: number;
}

declare interface Person {
  salary: number;
}
This post is licensed under CC BY 4.0 by the author.