众所周知,JS 中提供了 typeof 操作符,用来在 JS 中获取数据的类型。
console.log(typeof "周冬雨" ); // string
注:在TS中,使用 typeof 操作符来获取变量的类型,用法和js一样;
实际上,TS 也提供了 typeof 操作符:可以在类型上下文中引用变量或属性的类型(类型查询)。
使用场景:根据已有变量的值,获取该值的类型,来简化类型书写。
let p = { x: 1, y: 2 }
function formatPoint(point: { x: number; y: number }) {}
当然,我们也可以这样写:
function formatPoint(point: typeof p) {}
什么是类型上下文:
typeof 出现在类型注解的位置(参数名称的冒号后面)所处的环境就在类型上下文(区别于 JS 代码)。
注意:
typeof 只能用来查询变量或属性的类型,无法查询其他形式的类型(比如,函数调用的类型)。
比如:
console.log(typeof p.x); // number
下面的就会报错: typeof无法查询函数调用的类型
function add(num1: number, num2: number) {
return num1 + num2
}
let ret: typeof add(1, 2)