Structural typing

2 snippets across 2 stacks - Python, TypeScript

PYPython

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

Structural Typing Surprises

TS · Common Mistakes
Syntax
// TypeScript uses structural (shape) typing, not nominal (name) typing
Example
interface Cat {
  name: string;
  purr(): void;
}

interface Robot {
  name: string;
  purr(): void;
}

// These are the SAME type to TypeScript!
const robot: Robot = { name: "RoboCat", purr() { console.log("bzzz"); } };
const cat: Cat = robot; // No error - shapes match

// Excess property checking only works on object literals:
const direct: Cat = {
  name: "Whiskers",
  purr() {},
  // batteries: true, // Error: Object literal may only specify known properties
};

// But NOT on variables:
const obj = { name: "X", purr() {}, batteries: true };
const sneaky: Cat = obj; // No error - extra properties allowed from variables
Output
// Two types with the same shape are interchangeable, regardless of name

Note Structural typing means TypeScript cares about shape, not name. Excess property checking only catches extra properties on direct object literals - not on variables. This often surprises developers from C#/Java backgrounds. Use branded types if you need nominal distinction.

Frequently asked questions

How does Python handle structural typing?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Protocols (Structural Typing)" snippet in Python uses `from typing import Protocol`.
Which code does the Python example use?
The "Protocols (Structural Typing)" snippet uses `from typing import Protocol`, from the Classes & OOP section of the Python cheat sheet.
Which stacks cover "structural typing" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Protocols (Structural Typing)": Protocols enable duck-typing with static type checking. Classes do not need to explicitly inherit from the Protocol; they just need matching methods.