下面把 Python 开发者最常用 的语言要素——基础类型、控制语句、函数——逐条映射到 TypeScript,给出“最小差异”代码示例。
阅读时可直接复制到 TS Playground 运行验证。
1️⃣ 基本数字 & 字符串
Python
age: int = 18
price: float = 9.99
name: str = "Alice"
name = "Alice" # 动态推断
greeting = f"Hello, {name}" # f-string
TypeScript
const age: number = 18; // 所有数字都统一为 number
const price: number = 9.99;
const name: string = "Alice";
let name: string = "Alice";
let greeting = `Hello, ${name}`; // 模板字符串
2️⃣ 布尔 & None / null
Python True/False(首字母大写)
flag: bool = True
empty: None = None
TypeScript true/false(小写)
const flag: boolean = true;
const empty: null = null; // undefined 也可
3️⃣ 列表 ↔ 数组
Python 动态类型列表
nums: list[int] = [1, 2, 3]
mixed: list[Any] = [1, "x"]
nums = [1, 2, 3] # 可混合类型
nums.append("4") # 允许添加字符串
TypeScript 需统一元素类型
const nums: number[] = [1, 2, 3];
const mixed: (number | string)[] = [1, "x"];
// 或使用泛型写法 Array<number>
let nums: number[] = [1, 2, 3]; // 仅允许数字
nums.push(4); // 合法
nums.push("5"); // 编译报错
4️⃣ 元组 ↔ 元组
Python 固定长度,元素类型可混合
coord: tuple[int, int] = (10, 20)
point = (10, "x") # (int, str)
TypeScript 需明确定义每个位置类型
const coord: [number, number] = [10, 20];
let point: [number, string] = [10, "x"];
5️⃣ 字典 ↔ 对象 / Map / Record
Python dict 键值对
person: dict[str, int] = {"age": 30}
user = {"name": "Alice", "age": 30}
TypeScript 接口定义结构
// 最常用的对象字面量
const person: Record<string, number> = { age: 30 };
// 如果键固定,可写接口
interface Person { age: number; }
const p: Person = { age: 30 };
interface User {
name: string;
age: number;
}
let user: User = { name: "Alice", age: 30 };
6️⃣ 集合 ↔ Set
Python
s: set[int] = {1, 2, 3}
TypeScript
const s: Set<number> = new Set([1, 2, 3]);
7️⃣ 控制语句
if / elif / else
Python 缩进控制作用域
if age < 18:
print("minor")
elif age == 18:
print("just 18")
else:
print("adult")
TypeScript 花括号明确作用域
if (age < 18) {
console.log("minor");
} else if (age === 18) {
console.log("just 18");
} else {
console.log("adult");
}
for 循环
Python:for...in 遍历序列
for n in [1, 2, 3]:
print(n)
TypeScript:类 C 风格或 for...of
// 类 C 循环
for (let i = 0; i < 5; i++) {
console.log(i);
}
// 遍历数组
for (const n of [1, 2, 3]) {
console.log(n);
}
while / break / continue
Python
i = 0
while i < 3:
print(i)
i += 1
TypeScript
let i = 0;
while (i < 3) {
console.log(i);
i += 1;
}
8️⃣ 函数
普通函数
Python:动态参数与返回值
def add(a: int, b: int = 0) -> int:
return a + b
TypeScript:需声明参数和返回类型
function add(a: number, b = 0): number {
return a + b;
}
// 箭头函数写法
const add2 = (a: number, b = 0): number => a + b;
匿名函数
Python:lambda
square = lambda x: x ** 2
TypeScript:箭头函数
const add2 = (a: number, b = 0): number => a + b;
const square = (x: number): number => x ** 2;
可变参数
Python
def sum_all(*args: int) -> int:
return sum(args)
TypeScript
function sumAll(...args: number[]): number {
return args.reduce((a, b) => a + b, 0);
}
关键字参数 / 对象形参
Python:默认值实现可选参数
def greet(name: str, *, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
TypeScript:显式标记 ?
function greet(name: string, { greeting = "Hello" }: { greeting?: string } = {}) {
return `${greeting}, ${name}!`;
}
9️⃣ 类 & 继承
Python
class Animal:
def __init__(self, name: str) -> None:
self.name = name
def speak(self) -> str:
return f"{self.name} makes a sound"
class Dog(Animal):
def speak(self) -> str:
return f"{self.name} barks"
TypeScript
class Animal {
constructor(public name: string) {}
speak(): string {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak(): string {
return `${this.name} barks`;
}
}
🔟 高级特性对比
- 类型联合(Union Types)
• Python:Union 类型注解
from typing import Union
def parse_input(data: Union[str, int]) -> str:
return str(data)
• TypeScript:原生联合类型 |
function parseInput(data: string | number): string {
return data.toString();
}
- 字面量类型
• Python:通过 Literal 实现
from typing import Literal
def set_direction(d: Literal["north", "south"]): ...
• TypeScript:原生支持字面量联合
function setDirection(d: "north" | "south") { ... }
1️⃣1️⃣ 列表推导式 ↔ Array.map/filter/reduce
Python
evens = [x * 2 for x in range(5)]
TypeScript
const evens = Array.from({ length: 5 }, (_, x) => x * 2);
1️⃣2️⃣ 模块导出导入
Python
# utils.py
def foo(): ...
# main.py
from utils import foo
TypeScript
// utils.ts
export function foo() {}
// main.ts
import { foo } from './utils';
小结速查表
| Python | TypeScript | 备注 |
|---|---|---|
int/float | number | 统一 |
list[T] | T[] | 数组 |
tuple[A, B] | [A, B] | 元组 |
dict[str, T] | Record<string, T> | 对象 |
set[T] | Set<T> | 集合 |
None | null / undefined | 二选一 |
def f(...) -> T | function f(...): T | 类型后置 |
*args | ...args: T[] | 剩余参数 |
| 类继承 | class A extends B | 相同 |
把这张表贴墙,日常写 TS 基本不会迷路。祝编码愉快!