附录A Python与TypeScript对照速查表
本附录提供Python与TypeScript常用语法对照,方便快速查阅。
A.1 基础语法对照
Section titled “A.1 基础语法对照”| Python | TypeScript | 说明 |
|---|---|---|
x = 1 | let x: number = 1 | 变量(显式类型) |
x: int = 1 | let x = 1 | 变量(类型推断) |
PI = 3.14 | const PI = 3.14 | 常量 |
| - | var x = 1 | 旧式变量(不推荐) |
| Python | TypeScript | 说明 |
|---|---|---|
int | number | 整数和浮点数 |
float | number | 无区分 |
str | string | 字符串 |
bool | boolean | 布尔值 |
bytes | Uint8Array | 字节数组 |
None | null / undefined | 空值 |
| Python | TypeScript | 说明 |
|---|---|---|
x: int | let x: number | 类型标注 |
def f(x: int) -> str: | function f(x: number): string {} | 函数类型 |
x: int | None | x: number | null | 联合类型 |
List[int] | number[] | 列表类型 |
Dict[str, int] | Record<string, number> | 字典类型 |
Tuple[int, str] | [number, string] | 元组类型 |
A.2 数据结构对照
Section titled “A.2 数据结构对照”| Python | TypeScript |
|---|---|
[] | [] |
[1, 2, 3] | [1, 2, 3] |
list(map(fn, items)) | items.map(fn) |
list(filter(fn, items)) | items.filter(fn) |
[x for x in items] | items.map(x => x) |
len(items) | items.length |
items[0] | items[0] |
items.append(x) | items.push(x) |
| Python | TypeScript |
|---|---|
{} | {} |
{"a": 1} | { a: 1 } |
d.keys() | Object.keys(d) |
d.values() | Object.values(d) |
d.items() | Object.entries(d) |
d.get("key", default) | d["key"] ?? default |
d.keys() | d2.keys() | new Set([...Object.keys(d), ...Object.keys(d2)]) |
集合/Set
Section titled “集合/Set”| Python | TypeScript |
|---|---|
set() | new Set() |
{1, 2, 3} | new Set([1, 2, 3]) |
a & b | [...a].filter(x => b.has(x)) |
a | b | new Set([...a, ...b]) |
a - b | [...a].filter(x => !b.has(x)) |
a ^ b | [...a].filter(x => !b.has(x)).concat([...b].filter(x => !a.has(x))) |
A.3 函数与模块对照
Section titled “A.3 函数与模块对照”| Python | TypeScript |
|---|---|
def f(x): | function f(x: type) {} |
def f(x=5): | function f(x: number = 5) {} |
*args | ...args: type[] |
lambda x: x * 2 | (x: number) => x * 2 |
def f(*, key=None): | function f(key?: type) {} |
yield | yield(生成器) |
| Python | TypeScript |
|---|---|
f(1, 2) | f(1, 2) |
f(key=value) | f({ key: value })(对象解构) |
f(*args) | f(...args) |
f(**kwargs) | f({ ...kwargs }) |
| Python | TypeScript |
|---|---|
import os | import * as os from "os" |
from math import pi | import { pi } from "math" |
from .utils import f | import { f } from "./utils" |
import pandas as pd | import pandas as pd from "pandas" |
from .. import utils | import * as utils from "../utils" |
| Python | TypeScript |
|---|---|
| 直接定义 | export const x = 1 |
__all__ = ["f"] | export { f } |
| 默认导出 | export default function() {} |
| 重新导出 | export { f } from "./module" |
A.4 常用库对照
Section titled “A.4 常用库对照”| Python | TypeScript |
|---|---|
json | JSON |
math | Math |
datetime | Date |
random | Math(随机用Math.random()) |
re | 内置正则/RegExp |
itertools | 无直接对应 |
functools | 内置数组方法 |
typing | 内置类型系统 |
常用第三方库
Section titled “常用第三方库”| Python | TypeScript |
|---|---|
numpy | ndarray(需库) |
pandas | DataFrame(需库) |
requests | fetch |
pydantic | zod / yup |
sqlalchemy | prisma / typeorm |
fastapi | express / fastify |
django | nextjs |
A.5 错误处理对照
Section titled “A.5 错误处理对照”try/except
Section titled “try/except”| Python | TypeScript |
|---|---|
try: ... except Exception as e: | try { ... } catch (e) { ... } |
raise ValueError("msg") | throw new Error("msg") |
except ValueError: | catch (e) { if (e instanceof Error) ... } |
finally: | finally { ... } |
| Python | TypeScript |
|---|---|
Exception | Error |
ValueError | new Error("msg") |
TypeError | new TypeError("msg") |
KeyError | new Error("msg")(Map用.get()) |
IndexError | 数组边界检查 |
NotImplementedError | new Error("Not implemented") |
A.6 类与面向对象对照
Section titled “A.6 类与面向对象对照”| Python | TypeScript |
|---|---|
class Foo: | class Foo {} |
def __init__(self, x): | constructor(x: type) {} |
self.x | this.x |
@property | get x(): type {} |
@staticmethod | static x() |
@classmethod | static x()(调用方式不同) |
| Python | TypeScript |
|---|---|
class A(B): | class A extends B {} |
super().__init__(x) | super(x) |
def method(self, x): | method(x: type): void {} |
__slots__ | 无直接对应 |
| Python | TypeScript |
|---|---|
_private | private |
__mangled | 无直接对应 |
| 公开 | public(默认) |
| 受限 | protected |
A.7 类型系统对照
Section titled “A.7 类型系统对照”| Python | TypeScript |
|---|---|
isinstance(x, int) | typeof x === "number" |
isinstance(x, (A, B)) | `x instanceof A |
typing.Union[A, B] | A | B |
typing.Optional[A] | A | null | undefined |
typing.Any | any |
typing.Mapping[K, V] | Record<K, V> |
typing.Sequence[T] | T[] |
| Python | TypeScript |
|---|---|
TypeVar("T") | <T> |
Generic[T] | interface Box<T> {} |
List[T] | T[] |
Callable[[A, B], R] | (a: A, b: B) => R |
A.8 常用代码模式对照
Section titled “A.8 常用代码模式对照”| Python | TypeScript |
|---|---|
async def f(): | async function f(): Promise<T> {} |
await x | await x |
asyncio.gather() | Promise.all() |
asyncio.sleep(1) | new Promise(r => setTimeout(r, 1000)) |
async for x in async_iter: | for await (const x of asyncIter) {} |
| Python | TypeScript |
|---|---|
a, b = (1, 2) | const [a, b] = [1, 2] |
x, *rest = items | const [x, ...rest] = items |
{a: x, b: y} | const { a: x, b: y } = obj |
| Python | TypeScript |
|---|---|
x if cond else y | cond ? x : y |
x or y | x ?? y |
x or default | x || default |
"a" in ["a", "b"] | ["a", "b"].includes("a") |
A.9 常用转换对照
Section titled “A.9 常用转换对照”| Python | TypeScript |
|---|---|
str(x) | String(x) |
int(x) | parseInt(x, 10) |
float(x) | parseFloat(x) |
repr(x) | JSON.stringify(x) |
f"{x} is {y}" | `${x} is ${y}` |
JSON操作
Section titled “JSON操作”| Python | TypeScript |
|---|---|
json.dumps(obj) | JSON.stringify(obj) |
json.loads(s) | JSON.parse(s) |
| Python | TypeScript |
|---|---|
datetime.now() | new Date() |
datetime.fromisoformat(s) | new Date(s) |
dt.isoformat() | dt.toISOString() |
本速查表涵盖了Python与TypeScript之间的主要语法对应关系。实际使用中可能存在细微差异,请参考各章节的详细说明。