Record

2 snippets across 2 stacks - Python, TypeScript

Also written as Record

PYPython

Dataclasses

PY · Classes & OOP
Syntax
from dataclasses import dataclass
@dataclass
class Name:
    field: type
Example
from dataclasses import dataclass, field

@dataclass
class Product:
    name: str
    price: float
    tags: list[str] = field(default_factory=list)

    @property
    def display_price(self) -> str:
        return f"${self.price:.2f}"

p = Product("Widget", 9.99, ["sale"])
print(p)
print(p.display_price)
Output
Product(name='Widget', price=9.99, tags=['sale'])
$9.99

Note Dataclasses auto-generate __init__, __repr__, and __eq__. Use field(default_factory=list) for mutable defaults, never a bare [] as a default.

TSTypeScript

Record<Keys, Value>

TS · Utility Types
Syntax
type Result = Record<KeyType, ValueType>;
Example
type Role = "admin" | "editor" | "viewer";

interface Permission {
  canRead: boolean;
  canWrite: boolean;
  canDelete: boolean;
}

const rolePermissions: Record<Role, Permission> = {
  admin:  { canRead: true,  canWrite: true,  canDelete: true },
  editor: { canRead: true,  canWrite: true,  canDelete: false },
  viewer: { canRead: true,  canWrite: false, canDelete: false },
};
Output
// Record forces every Role to have a Permission entry

Note When Keys is a union of string literals, Record ensures every literal is present - great for exhaustive mappings. Record<string, T> is equivalent to { [key: string]: T } and does not enforce specific keys.

Frequently asked questions

How does Python handle record?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Dataclasses" snippet in Python uses `from dataclasses import dataclass`.
Which code does the Python example use?
The "Dataclasses" snippet uses `from dataclasses import dataclass`, from the Classes & OOP section of the Python cheat sheet.
Which stacks cover "record" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Dataclasses": Dataclasses auto-generate __init__, __repr__, and __eq__. Use field(default_factory=list) for mutable defaults, never a bare [] as a default.