typeof 型別運算子
JavaScript 已經存在一個 typeof 運算子,你可以將其用於表示式上下文
tsTry// Prints "string"console .log (typeof "Hello world");
TypeScript 增加了一個 typeof 運算子,你可以在型別上下文中使用它來引用變數或屬性的型別
tsTrylets = "hello";letn : typeofs ;
對於基本型別,這並沒有太大用處,但結合其他型別運算子,你可以使用 typeof 來方便地表達許多模式。例如,我們先來看預定義的型別 ReturnType<T>。它接收一個函式型別併產生其返回型別
tsTrytypePredicate = (x : unknown) => boolean;typeK =ReturnType <Predicate >;
如果我們嘗試在一個函式名上使用 ReturnType,我們會看到一個具有指導意義的錯誤
tsTryfunctionf () {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
tsTryfunctionf () {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?");