简体   繁体   English

错误 TS2571:对象在打字稿中属于“未知”类型

[英]error TS2571: Object is of type 'unknown' in typescript

hello i need help to resolve this error你好我需要帮助来解决这个错误

try{

} catch {
  let errMsg;
  if (error.code === 11000) {
    errMsg = Object.keys(error.keyValue)[0] + "Already exists";
  }
  return res.status(500).json({ msg: errMsg });
}

console.log(error);
  

=>error TS2571: Object is of type 'unknown' =>错误TS2571:对象的类型为“未知”

You can set useUnknownInCatchVariables as false in tsconfig.json .您可以在tsconfig.json 设置false

try {

} catch(err) { // the type of catch variable is any

}

But use any is not a safe way, handle all possible boundary conditions manually is much better.但是使用any并不是一种安全的方式,手动处理所有可能的边界条件要好得多。

catch(err: unknown) {
  if (err instanceof Error) { // narrow `err` from `unknown` to `Error`
    console.log(err.message);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM