面试题答案
一键面试函数参数的上下文类型推断工作原理
在TypeScript中,上下文类型推断是指TypeScript编译器能够根据代码的上下文,自动推断出某些表达式的类型。对于函数参数,当函数作为另一个函数的参数被传递时,TypeScript可以根据接收函数的参数类型要求,来推断传递函数的参数类型。
示例
// 定义一个接收函数作为参数的函数,其参数类型为 (string) => void
function callWithString(callback: (str: string) => void) {
callback('Hello');
}
// 这里传递的匿名函数参数,其参数类型会根据callWithString的要求自动推断为string
callWithString((arg) => {
console.log(arg.length); // 这里可以直接使用string类型的length属性,因为arg被推断为string类型
});
在上述示例中,callWithString
函数期望接收一个参数类型为string
的回调函数。当传递匿名函数(arg) => { console.log(arg.length); }
时,TypeScript根据callWithString
对回调函数参数类型的要求,自动推断出arg
的类型为string
,因此可以使用string
类型的length
属性。