使用 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