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

TypeScript try catch的err报Object is of type 'unknown'.ts(2571)如何定义类型

报错原因

TypeScript 4.4及以上版本默认开启了 useUnknownInCatchVariables 配置项,会强制将try...catch捕获的错误变量类型设为unknown,因此直接访问.code属性时无法通过类型校验。你实际使用的是v4.4.3版本的TS,自然会触发该报错。

解决方法

方法1:类型断言(最快捷,适合确定错误为Node.js系统错误的场景)

直接将err断言为Node.js内置的系统错误类型即可:

router.get('/cells', async (req, res) => {
  try {
    const result = await fs.readFile(fullPath, { encoding: 'utf-8' });
    res.send(JSON.parse(result));
  } catch (err) {
    if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
      await fs.writeFile(fullPath, '[]', 'utf-8');
      res.send([]);
    } else {
      throw err;
    }
  }
})

方法2:自定义类型守卫(更安全,适合多处需要判断错误类型的场景)

先编写运行时校验逻辑,避免类型断言骗过TS但实际运行出错:

// 先定义类型守卫函数
function isNodeError(err: unknown): err is NodeJS.ErrnoException {
  return err instanceof Error && 'code' in err;
}

// 调用处代码
router.get('/cells', async (req, res) => {
  try {
    const result = await fs.readFile(fullPath, { encoding: 'utf-8' });
    res.send(JSON.parse(result));
  } catch (err) {
    if (isNodeError(err) && err.code === 'ENOENT') {
      await fs.writeFile(fullPath, '[]', 'utf-8');
      res.send([]);
    } else {
      throw err;
    }
  }
})

方法3:关闭对应校验配置(不推荐,会降低全局类型安全性)

如果要恢复旧版本TS的默认行为,可以在tsconfig.json的compilerOptions中添加配置:

{
  "compilerOptions": {
    "useUnknownInCatchVariables": false
  }
}

VSCode TypeScript版本注意事项

VSCode默认使用自带的TS版本做语法校验,和全局安装的tsc、项目本地安装的TS版本可能存在差异。如果要统一使用项目本地版本,可以按cmd + shift + P,搜索「Select TypeScript Version」,选择「Use Workspace Version」即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:57:01