DEV Community

Bobby Hall Jr
Bobby Hall Jr

Posted on • Edited on

What is an interface in TypeScript

Hey this is an awesome post about interfaces 🙂

What is an interface ?

TypeScript interfaces define the structure of the code using properties, methods, events and TypeScript types (string, boolean, number... etc)

For example the Size interface below has 2 properties width, height and 2 methods getWidth(), getHeight(). All need to be of type string because thats what we defined in the interface.

This is an interface:

interface Size {
  width: string
  height: string
  getWidth(): string
  getWidth(): string
}

// Usage of the interface above
class Shapes implements Size {
  width: string
  height: string
  constructor(width: string, height: string) {
    this.width = width
    this.height = height
  }
  getWidth() {
    return this.width
  }
}
Enter fullscreen mode Exit fullscreen mode

With optional parameters:

interface Post {
  title: string
  content: string
  // Optional parameters have a "?" at the end. EX: "tags?"
  tags?: string[] // returns an array of strings
}
Enter fullscreen mode Exit fullscreen mode

With read-only properties

interface User {
  name: string;
  email: string;
  // By adding "readonly" before a property, that makes it "read-only"
  readonly dateCreated: Date.Now();
}
Enter fullscreen mode Exit fullscreen mode

With Functions

interface SumFunc {
  (a: number, b: number): number
}

// Usage
const add: SumFunc = (a, b) => {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

Extending an interface

// PetInterface
interface PetInterface {
  name: string
}

// DogInterface extends PetInterface
interface DogInterface extends PetInterface {
  breed: string
}

// Example usage
class Dog implements DogInterface {
  name: string = 'Air Bud'
  breed: string = 'German Shepard'
}

// CatInterface also extends PetInterface
interface CatInterface extends PetInterface {
  breed: string
}

// Example usage
class Cat implements CatInterface {
  name: string = 'Garfeild'
  breed: string = 'Tuxedo Cat'
}
Enter fullscreen mode Exit fullscreen mode

Generic interfaces

// Generics allow you to reuse functions
// "T" is a generic variable that we can assign later
interface PaginatedResponse<T> {
  data: T[] // returns an array of "T"
  nextPageUrl?: string
  previousPageUrl?: string
}

interface Post {
  title: string
  content: string
  tags?: string[]
}

// Usage
function loadDataFromApi() {
  fetch('/some/api/endpoint')
    .then((response) => response.json())
    // Usage: assigning "Post" to the "T" variable
    .then((data: PaginatedResponse<Post>) => console.log(data))
}
Enter fullscreen mode Exit fullscreen mode

Subscribe to my newsletter where you will get tips, tricks and challenges to keep your skills sharp. Subscribe to newsletter


Top comments (0)