Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

reactjs - Why does instanceof check return false when tsconfig target is set to es5 vs true when set to esnext?

I moved a working React component to its own repo/package in order to improve code maintainability.

When using the following tsconfig.json, instanceof check returns false when it should return 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"]
}

This is my first time moving a working React component to its own repo/package. Is it normal to use "target": "esnext"? I initially chose es5 based on what create-react-app uses.

The project is written in TypeScript (.tsx).

question from:https://stackoverflow.com/questions/65831356/why-does-instanceof-check-return-false-when-tsconfig-target-is-set-to-es5-vs-tru

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This issue is caused by a TypeScript edge case.

Object.setPrototypeOf(this, FooError.prototype); solved my issue.

Example:

class FooError extends Error {
  constructor(m: string) {
    super(m);

    // Set the prototype explicitly.
    Object.setPrototypeOf(this, FooError.prototype);
  }

  sayHello() {
    return "hello " + this.message;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...