首页 > 解决方案 > 为什么当 tsconfig target 设置为 es5 时 instanceof check 返回 false 而设置为 esnext 时返回 true?

问题描述

为了提高代码的可维护性,我将一个正常工作的 React 组件移到了它自己的 repo/package 中。

使用以下内容时tsconfig.jsoninstanceof请检查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) 编写的。

标签: reactjstypescript

解决方案


此问题是由 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;
  }
}

推荐阅读