Interface

3 snippets across 2 stacks — Python, TypeScript

PYPython

Abstract Base Classes

PY · Classes & OOP
syntax
from abc import ABC, abstractmethod
class Base(ABC):
    @abstractmethod
    def method(self): ...
example
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...

class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius

    def area(self) -> float:
        return 3.14159 * self.radius ** 2

# shape = Shape()  # TypeError: can't instantiate abstract class
circle = Circle(5)
print(f"Area: {circle.area():.2f}")
output
Area: 78.54

Note Abstract classes cannot be instantiated directly. Subclasses must implement all @abstractmethod methods or they will also be abstract.

Protocols (Structural Typing)

PY · Classes & OOP
syntax
from typing import Protocol
class Drawable(Protocol):
    def draw(self) -> None: ...
example
from typing import Protocol

class Saveable(Protocol):
    def save(self, path: str) -> None: ...

class Document:
    def save(self, path: str) -> None:
        print(f"Saved to {path}")

def backup(item: Saveable, dest: str) -> None:
    item.save(dest)

backup(Document(), "/tmp/doc.txt")
output
Saved to /tmp/doc.txt

Note Protocols enable duck-typing with static type checking. Classes do not need to explicitly inherit from the Protocol; they just need matching methods.

TSTypeScript

Interface Declaration

TS · Interfaces
syntax
interface Name {
  property: Type;
  method(param: Type): ReturnType;
}
example
interface Product {
  id: string;
  name: string;
  price: number;
  getDisplayPrice(): string;
}

const laptop: Product = {
  id: "prod_001",
  name: "Developer Laptop",
  price: 1299,
  getDisplayPrice() {
    return `$${this.price.toFixed(2)}`;
  },
};
output
// laptop.getDisplayPrice() → "$1299.00"

Note Interfaces define the shape of objects. They are structurally typed — any object with the right shape satisfies the interface, no explicit 'implements' needed for plain objects.