Type Hints vs TypeScript
Adding static types to dynamic languages
Introduction
In this lesson, you'll learn about type hints vs typescript in JavaScript. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with adding static types to dynamic languages.
JavaScript has its own approach to adding static types to dynamic languages, which we'll explore step by step.
The JavaScript Way
Let's see how JavaScript handles this concept. Here's a typical example:
// Variable types
let name: string = "Alice";
let age: number = 30;
let scores: number[] = [90, 85, 92];
// Function signatures
function greet(name: string, times: number = 1): string {
return ("Hello, " + name + "! ").repeat(times).trim();
}
// Optional / null
function findUser(id: number): string | null {
return null;
}
// Union
function process(val: number | string): string {
return String(val);
}
// Interface (like TypedDict)
interface User {
id: number;
name: string;
email: string;
}Comparing to Python
Here's how you might have written similar code in Python:
from typing import Optional, Union, List, Dict, Tuple
# Variable annotations
name: str = "Alice"
age: int = 30
scores: List[int] = [90, 85, 92]
# Function signatures
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
# Optional (can be None)
def find_user(id: int) -> Optional[str]:
return None
# Union
def process(val: Union[int, str]) -> str:
return str(val)
# TypedDict
from typing import TypedDict
class User(TypedDict):
id: int
name: str
email: strYou may be used to different syntax or behavior.
Python type hints are optional annotations checked by mypy/pyright
You may be used to different syntax or behavior.
TypeScript types are enforced at compile time
You may be used to different syntax or behavior.
Optional[T] ≈ T | null
You may be used to different syntax or behavior.
TypedDict ≈ interface
Step-by-Step Breakdown
1. Basic Type Annotations
Syntax is almost identical. Python uses : Type after the variable; TypeScript does the same.
name: str = "Alice"
age: int = 30let name: string = "Alice";
let age: number = 30;2. Optional Values
Optional[T] in Python means T | None. TypeScript uses T | null or T | undefined.
def find(id: int) -> Optional[str]: ...function find(id: number): string | null { ... }3. Structured Types
TypedDict in Python and interface in TypeScript both define object shapes.
class User(TypedDict):
id: int
name: strinterface User {
id: number;
name: string;
}Common Mistakes
When coming from Python, developers often make these mistakes:
- Python type hints are optional annotations checked by mypy/pyright
- TypeScript types are enforced at compile time
- Optional[T] ≈ T | null
Key Takeaways
- str/int/bool → string/number/boolean
- Optional[T] → T | null
- TypedDict → interface