how to define an interface in typescript

In TypeScript, we can define interfaces that describe the shape of objects. An interface can be defined using the interface keyword followed by the name of the interface and a set of properties and their types. Here is an example:

interface Person {
  name: string;
  age: number;
  address?: string;
72 chars
6 lines

In the above example, we have defined an interface named Person. It has name and age properties that are required and of types string and number respectively. We have also defined an optional address property of type string.

We can create an object that conforms to this interface as follows:

const john: Person = {
  name: 'John',
  age: 30,
  address: '123 Main Street'
81 chars
6 lines

This object john has a name property of type string, an age property of type number, and an optional address property of type string.

Interfaces play a big role in TypeScript's type checking system, as they allow us to define strict contracts between different parts of our code.

gistlibby LogSnag