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
}
}
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
}
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();
}
With Functions
interface SumFunc {
(a: number, b: number): number
}
// Usage
const add: SumFunc = (a, b) => {
return a + b
}
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'
}
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))
}
Top comments (0)