Skip to content

附录A Python与TypeScript对照速查表

本附录提供Python与TypeScript常用语法对照,方便快速查阅。


PythonTypeScript说明
x = 1let x: number = 1变量(显式类型)
x: int = 1let x = 1变量(类型推断)
PI = 3.14const PI = 3.14常量
-var x = 1旧式变量(不推荐)
PythonTypeScript说明
intnumber整数和浮点数
floatnumber无区分
strstring字符串
boolboolean布尔值
bytesUint8Array字节数组
Nonenull / undefined空值
PythonTypeScript说明
x: intlet x: number类型标注
def f(x: int) -> str:function f(x: number): string {}函数类型
x: int | Nonex: number | null联合类型
List[int]number[]列表类型
Dict[str, int]Record<string, number>字典类型
Tuple[int, str][number, string]元组类型

PythonTypeScript
[][]
[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)
PythonTypeScript
{}{}
{"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)])
PythonTypeScript
set()new Set()
{1, 2, 3}new Set([1, 2, 3])
a & b[...a].filter(x => b.has(x))
a | bnew 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)))

PythonTypeScript
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) {}
yieldyield(生成器)
PythonTypeScript
f(1, 2)f(1, 2)
f(key=value)f({ key: value })(对象解构)
f(*args)f(...args)
f(**kwargs)f({ ...kwargs })
PythonTypeScript
import osimport * as os from "os"
from math import piimport { pi } from "math"
from .utils import fimport { f } from "./utils"
import pandas as pdimport pandas as pd from "pandas"
from .. import utilsimport * as utils from "../utils"
PythonTypeScript
直接定义export const x = 1
__all__ = ["f"]export { f }
默认导出export default function() {}
重新导出export { f } from "./module"

PythonTypeScript
jsonJSON
mathMath
datetimeDate
randomMath(随机用Math.random())
re内置正则/RegExp
itertools无直接对应
functools内置数组方法
typing内置类型系统
PythonTypeScript
numpyndarray(需库)
pandasDataFrame(需库)
requestsfetch
pydanticzod / yup
sqlalchemyprisma / typeorm
fastapiexpress / fastify
djangonextjs

PythonTypeScript
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 { ... }
PythonTypeScript
ExceptionError
ValueErrornew Error("msg")
TypeErrornew TypeError("msg")
KeyErrornew Error("msg")(Map用.get())
IndexError数组边界检查
NotImplementedErrornew Error("Not implemented")

PythonTypeScript
class Foo:class Foo {}
def __init__(self, x):constructor(x: type) {}
self.xthis.x
@propertyget x(): type {}
@staticmethodstatic x()
@classmethodstatic x()(调用方式不同)
PythonTypeScript
class A(B):class A extends B {}
super().__init__(x)super(x)
def method(self, x):method(x: type): void {}
__slots__无直接对应
PythonTypeScript
_privateprivate
__mangled无直接对应
公开public(默认)
受限protected

PythonTypeScript
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.Anyany
typing.Mapping[K, V]Record<K, V>
typing.Sequence[T]T[]
PythonTypeScript
TypeVar("T")<T>
Generic[T]interface Box<T> {}
List[T]T[]
Callable[[A, B], R](a: A, b: B) => R

PythonTypeScript
async def f():async function f(): Promise<T> {}
await xawait 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) {}
PythonTypeScript
a, b = (1, 2)const [a, b] = [1, 2]
x, *rest = itemsconst [x, ...rest] = items
{a: x, b: y}const { a: x, b: y } = obj
PythonTypeScript
x if cond else ycond ? x : y
x or yx ?? y
x or defaultx || default
"a" in ["a", "b"]["a", "b"].includes("a")

PythonTypeScript
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}`
PythonTypeScript
json.dumps(obj)JSON.stringify(obj)
json.loads(s)JSON.parse(s)
PythonTypeScript
datetime.now()new Date()
datetime.fromisoformat(s)new Date(s)
dt.isoformat()dt.toISOString()

本速查表涵盖了Python与TypeScript之间的主要语法对应关系。实际使用中可能存在细微差异,请参考各章节的详细说明。