这个错误通常出现在 TypeScript 代码中,是由于在使用一个类型为 string | AnyObject | ArrayBuffer
的变量时,使用了 message
属性,而 TypeScript 不清楚这个变量的类型到底是什么,因此报出了该错误提示。
为了解决这个问题,可以先使用类型断言(Type Assertion)将变量的类型指定为 string
,然后再使用 message
属性,例如:
const myVariable: string | AnyObject | ArrayBuffer = 'Hello, world!'
if (typeof myVariable === 'string') {
console.log(myVariable.message) // 报错:类型“string”上不存在属性“message”。
}
if (typeof myVariable === 'string') {
console.log((myVariable as unknown as { message: string }).message) // 不再报错
}
在这个例子中,第一个 if 语句会报错,因为 typeof myVariable
的结果是 string
,而 string
类型没有 message
属性,因此 TypeScript 提示不存在该属性。为了解决这个问题,可以使用类型断言将 myVariable
的类型转换为一个拥有 message
属性的对象类型,并且在进行类型断言时需要使用 unknown
类型。
第二个例子
data: res.data.message,//返回数据
//message 报错 类型“string | AnyObject | ArrayBuffer”上不存在属性“message”。类型“string”上不存在属性“message”
data: (res.data as {message?:any}).message,//返回数据
//改成这样就行了