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

TypeScript报错:属性不存在于类型,hasOwnProperty判断失效如何解决?

解决TypeScript中OptionType类型的取值错误问题

首先,你定义的联合类型如下:

type OptionType = {value: number | string} | number | string;

尝试执行以下代码获取值时(注意代码中存在data与value的拼写不一致问题,需修正为统一变量名):

// 修正拼写后的代码示例
const finalValue = Object.prototype.hasOwnProperty.call(value, "value") ? value.value : value;

TypeScript抛出错误:

Property 'value' does not exist on type 'string | number | OptionType'

问题原因

TypeScript无法通过Object.prototype.hasOwnProperty.call的调用自动推断出变量此时属于联合类型中的对象变体,因此无法确认value属性是否存在。

解决方法

方法一:自定义类型守卫函数

创建一个类型守卫函数来明确判断变量是否为带value属性的对象类型,TypeScript会根据该函数的返回值自动缩小类型范围:

function isOptionWithValue(input: OptionType): input is {value: number | string} {
  return typeof input === 'object' && input !== null && 'value' in input;
}

// 使用类型守卫
const finalValue = isOptionWithValue(value) ? value.value : value;

方法二:内联类型断言结合类型检查

如果希望保持内联逻辑,可以在确认类型后使用类型断言:

const finalValue = (typeof value === 'object' && value !== null && 'value' in value) 
  ? (value as {value: number | string}).value 
  : value;

注意事项

  • 务必修正代码中data和value的拼写不一致问题,否则即使类型问题解决,运行时也会出现错误。
  • 使用typeof input === 'object'时要额外判断input !== null,因为null的类型也是object,但它没有任何属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 04:56:22