You need to enable JavaScript to run this app. 如何构造仅接受对象类型、排除所有基础类型的类型别名?
优惠活动
大模型
产品
解决方案
定价
更多

如何构造仅接受对象类型、排除所有基础类型的类型别名?

解决方案

可以直接使用 TypeScript 内置的 object 类型,该类型本身就代表所有非原始类型,正好符合你的需求:会自动排除 string、number、boolean、bigint、symbol、null、undefined 所有基础类型,仅接受普通对象、数组、函数、类实例等非原始类型。

示例代码

// 直接复用内置 object 类型即可
type OnlyObject = object;

// 合法性测试
const test1: OnlyObject = {}; // 类型校验通过
const test2: OnlyObject = []; // 类型校验通过
const test3: OnlyObject = new Map(); // 类型校验通过
const test4: OnlyObject = () => {}; // 类型校验通过

const test5: OnlyObject = 'test'; // 类型报错,基础类型不允许
const test6: OnlyObject = 123; // 类型报错
const test7: OnlyObject = true; // 类型报错
const test8: OnlyObject = null; // 类型报错

自定义限制场景

如果你需要更严格的过滤,比如只接受普通键值对象和数组,排除函数、Date、正则这类特殊非原始类型,可以手写自定义逻辑:

// 先定义所有需要排除的基础类型
type Primitive = string | number | boolean | null | undefined | symbol | bigint;
// 再额外排除你不需要的非原始类型
type OnlyPlainObjectOrArray = Exclude<unknown, Primitive | Function | Date | RegExp>;

// 测试
const obj: OnlyPlainObjectOrArray = {name: 'aaa'}; // 校验通过
const arr: OnlyPlainObjectOrArray = [1,2,3]; // 校验通过
const func: OnlyPlainObjectOrArray = () => {}; // 类型报错
const date: OnlyPlainObjectOrArray = new Date(); // 类型报错

注意:不要误用 {} 类型,{} 代表所有拥有 toString、valueOf 方法的类型,会包含所有非 null/undefined 的基础类型,完全不符合你的需求。

内容的提问来源于stack exchange,提问作者Gonzalo Rocha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 00:42:01