Typeof 型別運算子

typeof 型別運算子

JavaScript 已經存在一個 typeof 運算子,你可以將其用於表示式上下文

ts
// Prints "string"
console.log(typeof "Hello world");
Try

TypeScript 增加了一個 typeof 運算子,你可以在型別上下文中使用它來引用變數或屬性的型別

ts
let s = "hello";
let n: typeof s;
let n: string
Try

對於基本型別,這並沒有太大用處,但結合其他型別運算子,你可以使用 typeof 來方便地表達許多模式。例如,我們先來看預定義的型別 ReturnType<T>。它接收一個函式型別併產生其返回型別

ts
type Predicate = (x: unknown) => boolean;
type K = ReturnType<Predicate>;
type K = boolean
Try

如果我們嘗試在一個函式名上使用 ReturnType,我們會看到一個具有指導意義的錯誤

ts
function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<f>;
'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?2749'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?
Try

請記住,型別不是一回事。要引用f 所具有的型別,我們使用 typeof

ts
function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;
type P = { x: number; y: number; }
Try

限制

TypeScript 有意限制了你可以對哪些表示式使用 typeof

具體來說,僅允許對識別符號(即變數名)或其屬性使用 typeof。這有助於避免陷入誤區,即編寫了你以為正在執行但實際上並未執行的程式碼

ts
// Meant to use = ReturnType<typeof msgbox>
let shouldContinue: typeof msgbox("Are you sure you want to continue?");
',' expected.1005',' expected.
Try

TypeScript 文件是一個開源專案。透過 傳送 Pull Request 幫助我們改進這些頁面 ❤

此頁面的貢獻者
OTOrta Therox (4)
JLJimmy Liao (1)

最後更新:2026 年 3 月 27 日