You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TypeScript中如何判断对象是否属于自定义类型?

问题核心原因

你想实现的typeof input === Human写法无法直接生效,因为TypeScript的所有类型定义都是编译时语法,编译为JavaScript运行时之后,所有自定义类型都会被完全擦除,运行环境中根本不存在Human这个标识符,自然不可能直接通过运行时操作符判断类型归属。

可行实现方案

方案1:手写类型谓词校验函数(无依赖,推荐普通场景使用)

这是TS原生支持的标准实现方式,通过类型谓词input is Human告诉TS,只要函数返回true,入参就符合Human类型,还能自动触发类型收窄。
示例代码如下:

// 自定义类型定义
type Human = {
  name: string;
  age: number;
}

// 类型校验函数
function isHuman(input: unknown): input is Human {
  // 先排除非对象、null的情况
  if (typeof input !== 'object' || input === null) return false;
  // 逐一校验属性是否存在、类型是否匹配
  return (
    'name' in input && typeof (input as Human).name === 'string' &&
    'age' in input && typeof (input as Human).age === 'number'
  );
}

使用示例:

const test1 = { name: '张三', age: 18 };
const test2 = { name: '李四', age: '18' };

console.log(isHuman(test1)); // true
console.log(isHuman(test2)); // false

if (isHuman(test1)) {
  // 这里TS会自动将test1识别为Human类型,调用属性不会报类型错误
  console.log(test1.name, test1.age);
}

如果需要严格匹配不允许额外属性,可以在校验逻辑里增加key数量的判断:

return (
  'name' in input && typeof (input as Human).name === 'string' &&
  'age' in input && typeof (input as Human).age === 'number' &&
  Object.keys(input).length === 2
);

方案2:第三方运行时校验库(适合复杂类型场景)

如果你的自定义类型结构复杂,手写校验逻辑成本高,可以使用专门的运行时类型校验库,只需要定义一次结构schema,就能自动生成对应的TS类型和校验函数,避免重复写属性校验逻辑。

内容的提问来源于stack exchange,提问作者developeen。

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:18:03