TypeScript: Why Python Devs Should Care

typescript python dev

If you’re a Python developer, TypeScript might seem distant. But the frontend landscape has shifted—TypeScript is now the default. And there are lessons for Python here too.

The State of TypeScript

TypeScript adoption has exploded:

It’s not optional anymore.

TypeScript for Python Developers

The Familiar Parts

Type hints look similar:

# Python
def greet(name: str) -> str:
    return f"Hello, {name}"
// TypeScript
function greet(name: string): string {
    return `Hello, ${name}`;
}

Interfaces vs TypedDict

# Python
from typing import TypedDict

class User(TypedDict):
    id: int
    name: str
    email: str

def process_user(user: User) -> None:
    print(user["name"])
// TypeScript
interface User {
    id: number;
    name: string;
    email: string;
}

function processUser(user: User): void {
    console.log(user.name);
}

Optional and Union Types

# Python
from typing import Optional, Union

def find_user(id: int) -> Optional[User]:
    ...

def get_value() -> Union[str, int]:
    ...
// TypeScript
function findUser(id: number): User | undefined {
    ...
}

function getValue(): string | number {
    ...
}

Generics

# Python
from typing import TypeVar, List

T = TypeVar('T')

def first(items: List[T]) -> T | None:
    return items[0] if items else None
// TypeScript
function first<T>(items: T[]): T | undefined {
    return items.length > 0 ? items[0] : undefined;
}

What TypeScript Does Better

1. Compile-Time Checks (That Actually Run)

interface Config {
    apiUrl: string;
    timeout: number;
}

function init(config: Config) {
    console.log(config.apiUrl);
}

init({ apiUrl: "https://api.example.com" });
// Error: Property 'timeout' is missing

TypeScript errors at compile time. Python type hints require a separate tool (mypy).

2. IDE Integration

TypeScript + VS Code = incredible experience:

Python’s type hints provide similar benefits, but TypeScript’s integration is tighter.

3. Strict by Default (Optional)

// tsconfig.json
{
    "compilerOptions": {
        "strict": true,
        "noImplicitAny": true,
        "strictNullChecks": true
    }
}

Forces you to handle nulls:

function getLength(s: string | undefined): number {
    return s.length;
    // Error: 's' is possibly 'undefined'
}

// Must handle null case
function getLength(s: string | undefined): number {
    if (s === undefined) return 0;
    return s.length;  // OK
}

Practical TypeScript

With React

// Type-safe props
interface ButtonProps {
    label: string;
    onClick: () => void;
    disabled?: boolean;
}

const Button: React.FC<ButtonProps> = ({ label, onClick, disabled = false }) => {
    return (
        <button onClick={onClick} disabled={disabled}>
            {label}
        </button>
    );
};

// Usage - TypeScript catches errors
<Button label="Click" onClick={() => console.log("clicked")} />  // OK
<Button label="Click" />  // Error: onClick is required

With APIs

// API response types
interface ApiResponse<T> {
    data: T;
    status: number;
    error?: string;
}

async function fetchUser(id: number): Promise<ApiResponse<User>> {
    const response = await fetch(`/api/users/${id}`);
    return response.json();
}

// Usage
const result = await fetchUser(1);
console.log(result.data.name);  // Autocomplete works!

With Zod (Runtime Validation)

import { z } from 'zod';

// Define schema
const UserSchema = z.object({
    id: z.number(),
    name: z.string(),
    email: z.string().email(),
});

// Infer TypeScript type from schema
type User = z.infer<typeof UserSchema>;

// Runtime validation
function processUser(data: unknown): User {
    return UserSchema.parse(data);  // Throws if invalid
}

Best of both worlds: compile-time types + runtime validation.

Lessons for Python

Run Your Type Checker

# Add to CI/CD
pip install mypy
mypy --strict your_project/

Type hints without mypy are just documentation.

Use Pydantic

Like Zod for Python:

from pydantic import BaseModel, EmailStr

class User(BaseModel):
    id: int
    name: str
    email: EmailStr

# Runtime validation + type hints
user = User(id=1, name="John", email="john@example.com")

Consider Strict Mode

# mypy.ini
[mypy]
strict = True

It hurts at first. It saves bugs later.

Learning Path for Python Devs

  1. Start with typed JavaScript: Write JS with JSDoc comments
  2. Basic TypeScript: Add types to existing JS
  3. Strict mode: Enable strictNullChecks
  4. Advanced types: Generics, conditional types

Final Thoughts

TypeScript won the frontend. Even if you’re a backend Python developer:

Learn enough to be dangerous.


Types are documentation that the computer enforces.

All posts