ข้ามไปยังเนื้อหา

Static Type Checking — mypy

ตอนเริ่มเขียน TypeScript ใหม่ ๆ คุณคงเคยเจอวินาทีที่ compiler จับ bug จริงได้ตั้งแต่ยังไม่ได้รันโค้ด type hints ของ Python ให้ประโยชน์แบบเดียวกันได้ ต่างกันตรงที่ interpreter ไม่เคยตรวจให้เลย งานตรวจจึงตกเป็นของ static analysis tool แยกต่างหากอย่าง mypy

มอง mypy เป็น tsc --noEmit เวอร์ชัน Python ได้เลย คืออ่าน annotation ของคุณแล้วรายงาน type error ออกมา โดยไม่ต้องรันหรือ compile อะไรทั้งสิ้น

รันในเทอร์มินัลของคุณ:

Terminal window
pip install mypy
# หรือ:
uv add --dev mypy
# ตรวจสอบไฟล์เดียว
mypy src/main.py
# ตรวจสอบทั้ง package
mypy src/
# โหมด strict (เทียบกับ tsconfig "strict: true")
mypy --strict src/
TypeScript
// TypeScript — types enforced by compiler
function greet(name: string): string {
return `Hello, ${name}!`;
}
function add(a: number, b: number): number {
return a + b;
}
// Generic
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
Python
# Python — types checked by mypy, ignored by interpreter
def greet(name: str) -> str:
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
return a + b
# Generic (Python 3.12+ syntax)
def first[T](arr: list[T]) -> T | None:
return arr[0] if arr else None
TypeScript
// TypeScript common types
const names: string[] = ["Alice", "Bob"];
const scores: Map<string, number> = new Map();
const user: { name: string; age: number } | null = null;
// Optional parameter
function find(id: number, strict?: boolean): string | null {
return null;
}
// Union
type Result = { ok: true; value: string } | { ok: false; error: string };
Python
# Python 3.10+ common types
from typing import Optional
names: list[str] = ["Alice", "Bob"]
scores: dict[str, int] = {}
user: dict[str, str | int] | None = None
# Optional parameter (None default = Optional)
def find(id: int, strict: bool = False) -> str | None:
return None
# TypedDict สำหรับ dict ที่มีโครงสร้างชัดเจน
from typing import TypedDict
class OkResult(TypedDict):
ok: bool
value: str
from typing import Optional
def double(x: int) -> int:
return x * 2
def greet(name: str) -> str:
return f"Hello, {name}!"
# สิ่งเหล่านี้ทำงานได้ปกติ
print(double(5))
print(greet("Alice"))
# Type hints ไม่หยุดสิ่งนี้ที่ runtime:
result = double("oops") # mypy จะ flag แต่ Python รันได้
print(result) # prints 'oopsoops' — string * 2 ทำซ้ำ!
TypeScript
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"target": "ES2022",
"module": "NodeNext"
}
}
Python
# pyproject.toml [tool.mypy] section
[tool.mypy]
python_version = "3.11"
strict = true # เปิดใช้ strict checks ทั้งหมด
warn_return_any = true
disallow_untyped_defs = true
ignore_missing_imports = true # สำหรับ third-party libs ที่ไม่มี type
ความสัมพันธ์ระหว่าง Python type hints กับ Python interpreter คืออะไร?
mypy flag ใดเปิดใช้ strict checks ทั้งหมด คล้ายกับ "strict: true" ใน tsconfig.json?
Python 3.10+ syntax สำหรับ "string หรือ None" เป็น return type คืออะไร?
mypy สัมพันธ์กับ Python เหมือนกับ _____ สัมพันธ์กับ TypeScript