What is an interface in typescript?
- Published on
- Authors
- Name
- Bobby Hall Jr
- @bobbyhalljr_dev
Hey this is an awesome post about interfaces 🙂
This is an interface:
interface Size {
width: string
height: string
getWisth(): string
getWisth(): string
}
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
}
Read-only properties
interface User {
name: string;
email: string;
// By adding "readonly" before a property, that makes it read-only"
readonly dateCreated: Date.Now();
}
Functions
interface SumFunc {
(a: number, b: number): number
}
// Usage
const add: SumFunc = (a, b) => {
return a + b
}
Extending an interface
// PetInterface
interface PetsInterface {
name: string
}
// DogInterface extends PetInterface
interface DogInterface extends PetsInterface {
breed: string
}
// Example usage
class Dog implements DogInterface {
name: string = 'Air Bud'
breed: string = 'German Shepard'
}
// CatInterface also extends PetInterface
interface CatInterface extends PetsInterface {
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('/som/api/endpoint')
.then((response) => response.json())
// Usage: assigning "Post" to the "T" variable
.then((data: PaginatedResponse<Post>) => console.log(data))
}