TypeScript 中 Object is of type ‘unknown’ 错误
当我们尝试访问具有未知类型的值的属性时,会发生“Object is of type unknown”错误。 要解决该错误,请在访问属性之前使用类型保护来缩小对象的类型,例如 if (err instanceof Error) {}。
下面是产生上述错误的示例代码
async function fetchData() {
try {
await Promise.resolve(42);
} catch (err) { // ?️ err is type unknown
// ⛔️ Error: object is of type unknown
console.log(err.message);
}
}
我们无法保证 catch 块中的错误会提前成为 Error 实例,因此 TypeScript 将其类型设置为 unknown 以避免任何意外的运行时错误。
为了解决这个问题,我们必须在访问特定属性之前使用类型保护来缩小对象的类型。
async function fetchData() {
try {
await Promise.resolve(42);
} catch (err) {
if (err instanceof Error) {
// ✅ TypeScript knows err is Error
console.log(err.message);
} else {
console.log('Unexpected error', err);
}
}
}
我们使用 instanceof 运算符来检查 err 是否是 Error 对象的实例。
如果是,我们就可以安全地访问 message 属性,因为所有 Error 实例都有一条字符串类型的消息。
对于未知类型,在获得 TypeScript 支持之前,我们首先必须检查当前存储在变量中的类型。
当无法提前知道变量存储的内容时,将使用该类型。 因此,在访问特定属性或方法之前,我们必须使用类型保护。
const something: unknown = 42;
if (typeof something === 'string') {
console.log(something.toUpperCase());
} else if (typeof something === 'number') {
console.log(something.toFixed(2));
}
例如,我们可以检查值的类型以便能够使用内置方法。
async function fetchData() {
try {
await Promise.resolve(42)
} catch (err) { // ?️ err is unknown
if (typeof err === 'object' && err !== null) {
console.log(err.toString());
} else {
console.log('Unexpected error', err);
}
}
}
我们检查 err 是否具有对象类型并且不为空。
null 检查似乎是随机的,但我们必须这样做,因为 null 在 JavaScript(和 TypeScript)中有一种对象类型。
console.log(typeof null); // ?️ "object"
TypeScript 并不总是将 catch 块中的错误键入为未知。 如果您不喜欢这种行为,您可以在 tsconfig.json 文件中将 useUnknownInCatchVariables 属性设置为 false,以将错误类型设置为 any。
{
"compilerOptions": {
// ... other stuff
"useUnknownInCatchVariables": false
}
}
如果您在 tsconfig.json 文件中将 useUnknownInCatchVariables 设置为 false,则错误变量将被键入为 any。
async function fetchData() {
try {
throw new Error('Something went wrong');
} catch (err) {
// ?️ err is type any
console.log(err.message); // ✅ OK
console.log(err.anything); // ✅ OK
}
}
但是,当使用这种方法时,您可能会遇到意外的运行时错误,因为无法确定抛出的是 Error 实例(尤其是在使用第 3 方包时)。
总结
当我们尝试访问具有未知类型的值的属性时,会发生“Object is of type unknown”错误。 要解决该错误,请在访问属性之前使用类型保护来缩小对象的类型,例如 if (err instanceof Error) {}。