我的博客

python &typescript 语法对照

Jul 25, 2026
python python语法
5分钟
852字

python &typescript 语法对照

一、类型

1
# TS: let name: string = "hello"
2
name: str = "hello"
3
4
# TS: let count: number = 42
5
count: int = 42
6
7
# TS: let price: number = 3.14
8
price: float = 3.14
9
10
# TS: let items: string[] = ["a", "b"]
11
items: list[str] = ["a", "b"]
12
13
# TS: let data: Record<string, number> = {a: 1}
14
data: dict[str, int] = {"a": 1}
15
7 collapsed lines
16
# TS: let maybe: string | null = None
17
maybe: str | None = None
18
# 注意 Python 的 "None" 是 None(大写 N),不是 null
19
20
# TS: function add(a: number, b: number): number
21
def add(a: int, b: int) -> int:
22
return a + b

二、class + 构造器

class 新建时:

  • ts 使用 class + construct
  • python 使用 class + def __init__

class 使用时:

  • ts 使用 new
  • python 直接调用,像 function 一样,如
    ()
1
# TS:
2
# class User {
3
# constructor(public name: string, private age: number) {}
4
# }
5
6
class User:
7
def __init__(self, name: str, age: int):
8
self.name = name # 公开属性,相当于 public
9
self._age = age # 带下划线 = 约定私有(private)
10
self.__secret = "xxx" # 双下划线 = 名称装饰(真私有,但不常用)

三、async/await - 两者一致

1
# TS: async function fetchData(): Promise<string>
2
async def fetch_data() -> str:
3
return "hello"
4
5
# TS: const data = await fetchData()
6
data = await fetch_data()
7
8
# TS: const stream = async function*() { yield "a" }
9
async def stream() -> AsyncGenerator[str, None]:
10
yield "a"
11
yield "b"

四、类型联合

1
# TS: let x: string | number = "hello"
2
x: str | int = "hello"
3
4
# TS: function greet(name?: string)
5
def greet(name: str | None = None):
6
...
7
8
# TS: const result = x ?? "default"
9
result = x or "default" # Python 用 or 代替 ??
10
# 或者更精确的条件判断:
11
result = "default" if x is None else x

python 中 None 不是 null,用 is 判断

1
# ✅ 对的
2
if x is None: ...
3
4
# ❌ 不对(虽然能跑但不规范)
5
if x == None: ...

五、try/except

python 中的 try/except 与 ts 中的 try/catch 基本一致

1
# TS:
2
# try { risky() } catch (e) { handle(e) }
3
4
try:
5
result = risky_function()
6
except ValueError as e:
7
print(f"值错误: {e}")
8
except Exception as e:
9
print(f"其他错误: {e}")
10
finally:
11
cleanup()

python 中抛出异常使用 raise ts 中抛出异常使用 throw

1
raise ValueError("xxx") # TS: throw new Error("xxx")

六、列表推导式

ts中的 map/filter,在 python 中使用列表推导式替代

1
# TS: arr.map(x => x * 2)
2
result = [x * 2 for x in [1, 2, 3]]
3
# → [2, 4, 6]
4
5
# TS: arr.filter(x => x > 1)
6
result = [x for x in [1, 2, 3] if x > 1]
7
# → [2, 3]
8
9
# TS: arr.map(x => x * 2).filter(x => x > 2)
10
result = [x * 2 for x in [1, 2, 3] if x * 2 > 2]
11
# → [4, 6]
12
13
# 字典也同理:
14
result = {k: v for k, v in {"a": 1}.items() if v > 0}

七、装饰器

1
# @property = 让方法像属性一样调用
2
class User:
3
def __init__(self, name: str):
4
self._name = name
5
6
@property # → user.name,不是 user.name()
7
def name(self) -> str:
8
return self._name
9
10
user = User("Alice")
11
print(user.name) # 不加括号

在 python 中装饰器相当于高阶函数 @xxx 就相当于 xxx(func)

八、相对导入

1
src/
2
llm/
3
provider.py
4
ollama.py ← 这里想 import provider
5
router.py
1
# 在 ollama.py 里:
2
from .provider import LLMProvider # 同目录下,用 .
3
# 相当于 TS: import { LLMProvider } from "./provider"
4
5
# 在 router.py 里:
6
from .ollama import OllamaProvider # 同目录下

. 代表「当前包目录」,要用 . 就必须保证文件被当成模块运行(python -m src.llm.demo),不能直接 python ollama.py

九、if name == “main”

1
# 任何 Python 文件底部都可以写这个
2
if __name__ == "__main__":
3
asyncio.run(main())

只有用 python xxx.py 直接运行这个文件时才执行。被别的文件 import 时不执行。相当于 TS/JS 里检测 import.meta === 'main'或检查request.main === module

总结:TS 与 Python 关键字映射

TSPython
let x: stringx: str
nullNone
=== / !==is / is not(用于 None)
`
??or(近似)
!not
const没有,不赋值就完事
throwraise
try/catch/finallytry/except/finally
async function / async () =>async def
yield*yield from
import { X } from "./y"from .y import X
class X { constructor() }class X: def __init__(self)
thisself(显式传参)
new X()X()(不需要 new)
本文标题:python &typescript 语法对照
文章作者:vu-ji
发布时间:Jul 25, 2026
Copyright 2026
站点地图