Explosion Pills
Explosion Pills

Reputation: 191819

Can't find variable Symbol using React Native with TypeScript

I'm using the ES6 Symbol in my React Native project. This works fine for iOS, but on Android I get Can't find variable: Symbol.

I'm using TypeScript, and I've tried various tsconfig.json:

{
  "compilerOptions": {
    "target": "es2015",
    "jsx": "react",
    "lib": ["dom", "es7"],
    "moduleResolution": "node"
  },
}

I've also tried lib: ["dom", "es6"] and ["dom", "es6", "es7"] as well as target: "es5".

How can I get Symbol to be properly handled by TypeScript for React Native on Android?

Upvotes: 1

Views: 1634

Answers (3)

Gregory R.
Gregory R.

Reputation: 1955

You can import these in your root index.js file without installing any dependencies:

import "core-js/stable";
import "regenerator-runtime/runtime";

Upvotes: 0

Aluan Haddad
Aluan Haddad

Reputation: 31873

This a TypeScript issue at all.

You are missing a polyfill.

As a transpiler, TypeScript transforms syntactic constructs so as to represent their behavior but it does not provide runtime libraries.

Install an es6-symbol polyfill like this one with your package manager of choice and everything will be well.

Symbol is a library, and outside the scope of transpilation in general, at least from the TypeScript team's perspective.

Part of the motivation for this is that you can choose your own polyfill implementations, giving you flexibility. Another that comes to mind is that a transpiler is often invoked well before it would have sufficient information to know if it could exclude a polyfill.

Note: Your --target is set to es2015 but you are experiencing difficulties on some platforms due to libraries that were specified in es2015 not being provided by the runtime. I strongly advise that you lower use --target es5 for the time being.

One more thing I suggest is being consistent in your config terminology.

"target": "es2015",
"lib": ["dom", "es7"],

is confusing and should be changed to

"target": "es2015",
"lib": ["dom", "es2016"],

for the sake of the reader

Upvotes: 0

Hunaid Hassan
Hunaid Hassan

Reputation: 742

You can use import 'core-js/es6/symbol' without having to add an npm dependency or copy pasting an polyfill

EDIT: I doubt that it is a TS problem. Android JS runtime doesn't have Symbol support. I had this problem in plain JSX too and fixed it using the snippet pasted above.

Upvotes: 3

Related Questions