— 任意类型变量
Optionalguard: (it: T) => boolean— 可选的附加断言函数,签名 (it: T) => boolean
true 当且仅当 obj 是非 null 对象(非数组)且 guard(若提供)返回 true
// 基础:指定 T 收窄
type TestA = { name?: string };
if (isInferObject<TestA>(obj)) {
console.log(obj.name || 'noname'); // obj: TestA
}
// 带 guard 做附加验证
type TestB = { name: string };
if (isInferObject<TestB>(obj, it => typeof it.name === 'string')) {
console.log(obj.name); // obj: TestB 且 name 是 string
}
// guard 可以是 TypeGuard,省略显式泛型
type WithVersion = { version: number };
const isWithVersion = (it: WithVersion): it is WithVersion =>
typeof it.version === 'number';
if (isInferObject(val, isWithVersion)) {
val.version += 1; // val: WithVersion
}
检查 obj 是否为对象(非 null、非数组),结果为真时推导 obj 为 T
与 isPlainObject 的区别:本函数不排除
Date、Map、Set、Error等内置类实例,只做最基础的typeof === 'object' && !Array.isArray()检查。 如需严格判断"纯对象",请用 isPlainObject。泛型行为:
Record<string, unknown>(it: T) => boolean, 但也可以传 TypeGuard 型函数((it: T) => it is T),TS 同样接受且行为一致