使用 typeof
typeof 用於區分 number,string,boolean 和 symbol 時的型別。其他字串常量不會出錯,但也不會用於縮小型別。
與 instanceof 不同,typeof 可以使用任何型別的變數。在下面的例子中,foo 可以輸入為 number | string 而沒有問題。
這段程式碼( 試一試 ):
function example(foo: any) {
if (typeof foo === "number") {
// foo is type number in this block
console.log(foo + 100);
}
if (typeof foo === "string") {
// fooi is type string in this block
console.log("not a number: " + foo);
}
}
example(23);
example("foo");
版畫
123
not a number: foo