TypeScript 普通对象或类实例但排除数组、函数、null 的类型
结论
想用一个固定的、非泛型的类型注解,同时做到接受普通对象和类实例、拒绝数组/函数/null,并且属性收窄后不变成 any,TypeScript 现有类型系统做不到完全精确。object 能排除 null、undefined 和原始值,但数组和函数在结构上也满足 object;TypeScript 也没有可直接使用的否定类型来表示“是 object,但不是 array 或 function”。实际工程里,一般会在调用点用泛型条件类型过滤,或者用运行时守卫来保证精确性。
为什么这些方案不行
Record<PropertyKey, unknown> 或 { [key: string]: unknown } 会要求源类型有索引签名。类实例只有显式属性,没有隐式的字符串索引签名,所以 Test 不能赋给 Record<PropertyKey, unknown>,会报错:
error TS2345: Argument of type 'Test' is not assignable to parameter of type 'Record<PropertyKey, unknown>'.
Index signature for type 'string' is missing in type 'Test'.
{ [key: string]: any } 能接受类实例,是因为 any 的可赋值性很宽松;但访问 item.id 时拿到的也会是 any,索引访问的类型检查基本失效。把值换成 unknown 后,又会回到索引签名约束,类实例仍然会被拒绝。
条件类型 Dict<T> 本身没问题,但它是个“类型函数”,必须拿到具体的 T 才能求值。写成非泛型别名时没有具体 T,因此不能直接拿来当函数参数或 Vue prop 的固定类型。
关于 negated types,TypeScript 没有可用的 not 或否定类型;microsoft/TypeScript#4196 是相关的功能请求。官方后续是否支持,要看官方仓库的状态;至少在当前类型系统里,不能把它当成已经可用的内置类型。
可用方案一:泛型条件类型过滤
如果还要保留具体属性类型,可以把过滤放到泛型函数上:
type PlainObjectOrInstance<T> =
T extends Function ? never :
T extends readonly unknown[] ? never :
T extends object ? T :
never;
function test<T extends object>(item: T & PlainObjectOrInstance<T>) {
if ("id" in item) {
// 这里 item.id 会收窄为 unknown(非 any);
// 若需要 number,请使用下面的运行时守卫,或把 T 约束到 { id: number }
console.log(item.id);
}
console.log(item);
}
class Test {
id = 23;
}
test(new Test()); // OK
test({ id: 22 }); // OK
test([]); // 类型错误
test(null); // 类型错误
test(() => []); // 类型错误
这里用 Function 判断函数,是为了避免在条件类型里引入 any。代价是它仍然只是泛型辅助,不是 function test(item: PlainObjectOrInstance) 这样的固定注解;Vue prop 这类场景也不能直接套。
可用方案二:运行时类型守卫
如果目标是在运行时严格排除数组、函数和 null,用守卫更直接:
function isObjectButNotArray(value: unknown): value is object {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
typeof value === "function" 的函数不会进入这个分支,所以函数被排除了;数组由 Array.isArray 排除;null 则被显式排除。要注意,它会接受所有非数组对象,包括 Date、Map 这类内置实例。如果你的“普通对象或类实例”也要排除这些内置对象,还得额外检查原型。
需要拿到 id 的具体类型时,可以在守卫里一并收窄:
function hasNumberId(value: unknown): value is { id: number } {
return (
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
"id" in value &&
typeof (value as { id?: unknown }).id === "number"
);
}
function test(item: unknown) {
if (!hasNumberId(item)) return;
console.log(item.id); // number
}
近似但非精确的非泛型写法
也有人用结构上的“缺失属性”来近似排除:
type PlainObjectOrInstance = object & {
length?: never;
call?: never;
};
它一般能拒绝数组(因为有 length)和函数(因为有 length/call),也能接受大多数类实例和普通对象,而且不会引入 any。但它在语义上并不精确:如果一个普通对象或类实例本身就有 length 或 call,就会被错误拒绝。所以不建议拿它当通用公共 API 的精确类型,只适合能接受这种误判的工程场景。
建议
- 需要严格保证:用运行时守卫
typeof value === "object" && value !== null && !Array.isArray(value),再按需检查属性。 - 需要在编译期过滤调用参数并保留属性类型:用泛型条件类型辅助函数。
- 需要固定非泛型注解:接受
object的宽泛性,或者接受近似结构类型的误判;不要指望 TypeScript 当前能精确表达“object 但不是 array/function”。
备注:内容仅供参考。
