reactjs - 为什么当 tsconfig target 设置为 es5 时 instanceof check 返回 false 而设置为 esnext 时返回 true?
问题描述
为了提高代码的可维护性,我将一个正常工作的 React 组件移到了它自己的 repo/package 中。
使用以下内容时tsconfig.json
,instanceof
请检查false
应返回的时间true
。
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"declaration": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "react-jsx",
"lib": ["dom", "dom.iterable", "esnext"],
"module": "commonjs",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"outDir": "lib",
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "es5"
},
"include": ["src"]
}
这是我第一次将一个正常工作的 React 组件移动到它自己的 repo/package 中。使用正常"target": "esnext"
吗?我最初是es5
根据create-react-app
用途来选择的。
该项目是用 TypeScript ( .tsx
) 编写的。
解决方案
此问题是由 TypeScript边缘案例引起的。
Object.setPrototypeOf(this, FooError.prototype);
解决了我的问题。
例子:
class FooError extends Error {
constructor(m: string) {
super(m);
// Set the prototype explicitly.
Object.setPrototypeOf(this, FooError.prototype);
}
sayHello() {
return "hello " + this.message;
}
}
推荐阅读
- angular - 使用 TemplateRefs 对 Angular 组件进行单元测试
- curl - Facebook 正在抛出“请指定与此广告一起运行的图像”。尝试制作广告时
- aws-glue - AWS Glue:爬虫无法识别 CSV 格式的时间戳列
- android - 使用 TWA 在 Google Play 上成功发布的 PWA 有异常行为
- azure - 将消息从一条服务总线复制到另一条服务总线的最佳方法是什么?
- vue.js - Bootstrap Modal Hide from VUE 方法
- vba - 在 Word 的整行中水平对齐单元格内容
- ruby-on-rails - Rails MiniTest,为什么这个过程没有成功而不是错误?
- reactjs - React 开发工具认为我的网站处于开发模式
- regex - 正则表达式在括号内找到第四个值