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)

最後更新:2024 年 3 月 21 日