TypeScript Version: 1.8.9
Expected behavior:
TS should be aware of require & Promise
Actual behavior:
TS errors appear for require & Promise.
var something = require('something'); // <-- Cannot find name 'require'
Promise<any> { // <-- Cannot find name 'Promise'
I'm able to work around the require issue by simply declaring a custom typing for it, but not with Promise. I'm wondering if these should be more of a default part of TypeScript?
declare var require:any;
For require, we have a module-agnostic way to import (i.e. it works in Node and with RequireJS).
import something = require('something');
Notice the only change is that we used the import keyword instead of var.
To use Promise, you'll either need to set the compiler option target to es2015 (which means that you won't get any down-level transformations to ES5, so watch out!), or use es6-shim.d.ts (which is the safer option).
The good news is that with 2.0 we're going to support scenarios where your standard library has ES2015 features like Promise, but TypeScript will still compiler down to ES5. See #6974.
Oh excellent, I'll try import first and see if that works. Just had some scenarios where webpack lazy loads things later didn't know if import could be used I'll try. Thanks Dan
You're welcome!
import statements don't actually work outside of the top-level, so if you need to do conditional loading, we have something called _module elision_, which is when we don't emit a call to require if a module is only used for types. You can then make a direct call to require and use the shape of the module using the typeof keyword. You can write something like the following if you need:
// "Elided" import.
import _foo = require("foo");
declare function require(name: string): any;
if (/*...*/) {
// Conditionally require the module "foo".
// Use the shape of '_foo' to describe the variable 'foo'.
let foo: typeof _foo = require("foo");
}
Here, we won't emit a call to require for _foo because we didn't use any of the values that _foo exports.
Like as mentioned above, this will be fixed in 2.0.
Until then, you can use the es6 shim:
typings install dt~es6-shim --global
This will clear up the issues with Promise not being found, as well as Map not being found.
@gregoryagu Installing es6 shim typings doesn't solve the issue for me. I'm using TS 2.0.6 and my es6-shim typings are included in my tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false,
"declaration": true,
"outDir": "./"
},
"include": [
"src/**/*.ts",
"node_modules/**/*.d.ts",
"node_modules/@types/**/*.ts",
"typings/**/*.d.ts"
],
"version": "2.0.0"
}
ERROR in node_modules/angular-ui-router/commonjs/common/common.d.ts
(339,58): error TS2304: Cannot find name 'Promise'
I am getting the same issue as @jogjayr
Most helpful comment
I am getting the same issue as @jogjayr