typeof
型別運算子
JavaScript 已經有一個 typeof
運算子,您可以在運算式內容中使用它
tsTry
// Prints "string"console .log (typeof "Hello world");
TypeScript 新增了一個 typeof
運算子,您可以在型別內容中使用它來參考變數或屬性的型別
tsTry
lets = "hello";letn : typeofs ;
這對於基本型別來說不太有用,但與其他型別運算子結合使用時,您可以使用 typeof
方便地表達許多模式。例如,讓我們從預先定義的型別 ReturnType<T>
開始。它會取得一個函式型別並產生其回傳型別
tsTry
typePredicate = (x : unknown) => boolean;typeK =ReturnType <Predicate >;
如果我們嘗試在函式名稱上使用 ReturnType
,我們會看到一個有幫助的錯誤訊息
tsTry
functionf () {return {x : 10,y : 3 };}type'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'?P =ReturnType <>; f
請記住,值和類型並不相同。若要參照值 f
的類型,我們使用 typeof
tsTry
functionf () {return {x : 10,y : 3 };}typeP =ReturnType <typeoff >;
限制
TypeScript 故意限制你可以使用 typeof
的表達式類型。
具體來說,只允許在識別碼(即變數名稱)或其屬性上使用 typeof
。這有助於避免寫出你認為正在執行但實際上並非如此的混淆程式碼
tsTry
// Meant to use = ReturnType<typeof msgbox>let',' expected.1005',' expected.shouldContinue : typeofmsgbox ( "Are you sure you want to continue?");