— 待检查的任意值
true 当且仅当 val 是函数,同时收窄为 T(默认 AnyFunction)
// 基础用法
if (isFunction(fn)) {
fn(); // fn: AnyFunction
}
// 泛型收窄 — 提取返回值类型
declare const maybeFn: unknown;
if (isFunction<() => string>(maybeFn)) {
const result: string = maybeFn(); // ✅ 类型正确收窄
}
// 泛型收窄 — 配合 ReturnType / Parameters
type MyFn = (a: number, b: string) => boolean;
if (isFunction<MyFn>(val)) {
type R = ReturnType<typeof val>; // boolean
type P = Parameters<typeof val>; // [number, string]
}
检查值是否为函数(包括箭头函数、class、async 函数等)
支持泛型收窄:传入具体函数类型后,守卫通过时
val被推断为T, 可配合ReturnType<T>/Parameters<T>提取返回值类型和参数元组。与 isConstructor 的区别:本函数接受所有函数类型, 包括没有
prototype的箭头函数。用于需要判断"是否可调用"的场景。