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

None & Truthiness

TypeScript มีค่า “ไม่มี” อยู่สองตัวคือ null กับ undefined แถมมีกฎ linting ทั้งชุด (strictNullChecks) ไว้คุมอีกที ส่วน Python มีตัวเดียวคือ None ทำหน้าที่เป็นทั้ง sentinel ที่แปลว่า “ไม่มีค่า” และเป็นค่าที่ฟังก์ชัน return กลับมาเองโดยปริยายเมื่อไม่ได้เขียน return อะไรไว้

คุณเปรียบเทียบกับ None ด้วย is (ไม่ใช่ ==) — รายละเอียดเพิ่มเติมอยู่ด้านล่าง

TypeScript
// TypeScript
let user: string | null = null;
let config: string | undefined = undefined;
// Nullish coalescing
const name = user ?? "Guest";
// Optional chaining
const len = user?.length ?? 0;
// Type narrowing
if (user !== null && user !== undefined) {
console.log(user.toUpperCase());
}
Python
# Python
user: str | None = None # str | None = Optional[str]
# Fallback with "or"
name = user or "Guest"
# Conditional expression (ternary)
length = len(user) if user is not None else 0
# Type narrowing
if user is not None:
print(user.upper())

กฎ falsy ของ Python คล้ายกับ JavaScript แต่เข้มงวดและสม่ำเสมอกว่า container ที่ว่างเปล่า ใด ๆ เป็น falsy ส่วน ตัวเลขที่ไม่ใช่ศูนย์ ใด ๆ เป็น truthy

ค่าFalsy ใน Python?Falsy ใน JS/TS?
Noneใช่null / undefined — ใช่
0ใช่ใช่
0.0ใช่ใช่
"" (string ว่าง)ใช่ใช่
[] (list ว่าง)ใช่ไม่ — [] เป็น truthy ใน JS
{} (dict ว่าง)ใช่ไม่ — {} เป็น truthy ใน JS
set() (set ว่าง)ใช่ไม่มี
() (tuple ว่าง)ใช่ไม่มี

สังเกต: array และ object ที่ว่างเปล่าเป็น truthy ใน JavaScript แต่เป็น falsy ใน Python เรื่องนี้ทำให้นักพัฒนา TS หลายคนสะดุดบ่อย ๆ

TypeScript
// TypeScript
console.log(Boolean([])); // true — empty array is truthy!
console.log(Boolean({})); // true — empty object is truthy!
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
if ([]) console.log("truthy"); // prints!
Python
# Python
print(bool([])) # False — empty list is FALSY
print(bool({})) # False — empty dict is FALSY
print(bool(0)) # False
print(bool("")) # False
print(bool(None)) # False
if []:
print("truthy") # does NOT print
else:
print("falsy") # prints
# Idiomatic: guard against empty containers
items = []
if not items:
print("No items found")

ใน Python is เช็ค identity (object เดียวกันในหน่วยความจำ) ส่วน == เช็ค equality (ค่าเท่ากัน) สำหรับ None ให้ใช้ is เสมอ — มี object None เพียงตัวเดียวในโปรเซส Python ดังนั้นการเช็ค identity จึงเป็นวิธีที่ถูกต้อง

TypeScript
// TypeScript — use strict equality
function process(data: string | null | undefined): void {
if (data === null || data === undefined) {
console.log("No data");
return;
}
console.log(data.toUpperCase());
}
Python
# Python — use "is None" / "is not None"
def process(data: str | None) -> None:
if data is None:
print("No data")
return
print(data.upper())
# Common pattern: default if None
def greet(name: str | None = None) -> str:
name = name or "World" # replaces None (or falsy) with default
return f"Hello, {name}!"
print(greet()) # Hello, World!
print(greet("Alice")) # Hello, Alice!
# None checks
x = None
print(x is None) # True
print(x is not None) # False
# Truthiness
print(bool([])) # False — empty list
print(bool([1])) # True — non-empty list
print(bool({})) # False — empty dict
print(bool({"a": 1})) # True
print(bool("")) # False — empty string
print(bool("hi")) # True
print(bool(0)) # False
print(bool(1)) # True
# None in function return
def get_user(user_id: int):
if user_id == 1:
return {"name": "Alice"}
return None # implicit in Python, but explicit is fine
user = get_user(99)
if user is None:
print("User not found")
user2 = get_user(1)
if user2 is not None:
print(f"Found: {user2['name']}")
ค่าใดของ Python ที่เทียบเท่าทั้ง `null` และ `undefined` ใน TypeScript?
`bool([])` คืนค่าอะไรใน Python?
ทำไมคุณจึงควรใช้ `x is None` แทน `x == None` ใน Python?
dict ว่าง `{}` ให้ผลเป็นอะไรในบริบท truthiness ของ Python?