Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors:

error TS2318: Cannot find global type 'Promise'.
...

This is a rundown of my npm setup:

"dependencies": {
    "@angular/common": "~2.4.0",
    ...
},
"devDependencies": {
    "jasmine": "^2.5.3",
    ...
}

As for my tsc-compiler configuration:

{
    "compilerOptions": {
        "target": "es5",
        ...
    }, "exclude": ["node_modules"]
}

Despite trying various solutions like deleting node_modules/, typings/, and adjusting dependencies, I only received more error messages. Can anyone offer assistance? My end goal is for others to clone my repository, execute npm install and npm run tsc, and seamlessly begin development.

Update1: Changing the target from es5 to es6 resolved the promise-related errors, but jasmine errors persist:

src/other.service.spec.ts(122,3): error TS2304: Cannot find name 'expect'.
...

Update2:

By aligning the dependencies with the angular-quickstart (https://github.com/angular/quickstart/blob/master/package.json), the issues were resolved. Thank you for the guidance!

Answer №1

You have overlooked including declarations for Promise and certain Array methods in your tsconfig.json. Make sure to add the "lib" property as shown below.

{
  "compilerOptions": {
    "lib": [
      "es2017",
      "dom"
    ],
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true
  }, 
  "exclude": ["node_modules"]
}

In addition, @rpadovani pointed out that you are missing some @types packages for test frameworks.

While there were suggestions in the comments to switch from

"target": "es5"
to
"target": "es2015"
, this decision should be made cautiously as it can severely limit the browsers that are supported unless a secondary transpiler is introduced.

In this scenario, updating the "target" property may not be necessary since Array methods like find can be added via a polyfill such as core-js, and Angular 2 itself fills in a global Promise by depending on zone.js. Therefore, instead of rushing to alter "target", consider configuring the "lib" option for better compatibility with newer runtimes/polyfills.

Note that changing the "target" setting also affects how TypeScript downlevels syntax during transpilation.

For instance,

Original TypeScript code

class A {
    http = new Http();
    async retrieve() {
        const data = await this.http
            .get('api/settings')
            .map(r => r.json() as Settings)
            .toPromise();
        const withId = { ...data, id: 1 };
    }
}

Generated JavaScript using

"target": "es5"

"use strict";
// JavaScript code here...

Generated JavaScript using

"target": "es2015"

"use strict";
// JavaScript code here...

Generated JavaScript using

"target": "es2017"

"use strict";
// JavaScript code here...

Generated JavaScript using

"target": "esnext"

"use strict";
// JavaScript code here...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is preventing us from assigning the jquery selector object to a different object's property for later use?

I'm facing an issue in the code below where I am trying to assign a jQuery selector object to another object property but it's not functioning as expected. Can you help me identify what mistake I might be making? index.html <html lang="en"&g ...

What strategies can be employed to improve generic inference skills?

Looking at the scenario provided below, how can we enhance code reusability in a manner similar to foobarA? interface F<T, U extends string> { t: T, f: (u: U) => void } declare const foo: <T, U extends string>(type: U) => F<T, U>; ...

Guide to displaying radio button value when updating a record

When updating a record in Node.js, I encounter an issue where the values for text input fields are rendered correctly, but the values for radio buttons and textarea in the update form do not appear. Can someone please advise on how to implement this? I am ...

What are the steps to resolve the vulnerability within vue-cli-service?

Recently, I set up a new project using @vue/cli 4.3.1 on a fresh installation of Ubuntu 19.10 with npm 6.14.4. Upon running npm install in the project directory, I received the following message: found 1 high severity vulnerability run `npm audit fix` t ...

I desire to share the JSON information and receive the corresponding response data

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

What is the best way to apply an SVG as the background-image for this text?

After examining the fiddle, it is clear that there is code to set the background of two spans to an image created with svg. The goal now is to achieve this dynamically using javascript (either jquery or raw) on the span with the "help" class, but unfortuna ...

"The `ngClass` directive allows for applying classes as an `object` rather than just a simple `class` value

When applying the class name like this: <tr *ngIf="crud.isCreate" [ngClass]="{'create' : crud?.isCreate}"> The class name is not being added correctly. In HTML, it appears as: <tr _ngcontent-yql-c9="" ng-reflect-ng-class="[object Obje ...

Is there a preferred method for correctly nesting components?

It may seem like a simple question, but I couldn't find the answer in the documentation or code examples. Consider this example: import { FlowIdentification } from "./flow-identification"; @customElement("bb-flow") export class R ...

What could be causing the undefined value of $routeParams?

I've encountered an issue while attempting to utilize a service for managing an http request: angular .module('app') .factory('stats', function($http){ return { getStats: function(path) { ...

How can I locate ThreeJS coordinates within the Panoramic GUI?

While I've dabbled with ThreeJS in the past, I'm currently working on a new project that involves setting up hotspots in a panoramic view. I vaguely recall using the camera dolly tool from this link to visualize camera locations. However, I' ...

Swapping the content of the API response with Angular 11 in the HTML

When the output of row.remarks is 1, I want to display it as "passed" and when it's 0, I want it to be displayed as "fail" in the HTML while using mat-table. HTML <ng-container matColumnDef="remarks"> <th class="font& ...

The alert feature is triggered when any button is pressed

I am dynamically adding buttons and assigning an event to them: $(document).on("click", ".del-but", remove); Within the remove function, I have a confirm dialog that triggers for each button added (3 buttons => 3 times) function remove() { ...

Displaying information collected from a submission form

I am in the process of designing a cheerful birthday card and I need to transfer data from a form to the birthday card page. How can I take information from the first div (which contains the form) and display that data in the second div? <!DOCTYPE ...

"Learn an effective method for presenting JSON variable data in a Bootstrap modal with a clean design using three distinct columns

I have successfully loaded JSON data into my HTML page using JQuery. By clicking a button, I can trigger a bootstrap modal that displays the content of the JSON variable. However, there is an issue with how the JSON data is displayed. I need the data to b ...

Discovering the earliest and latest dates within an array of date strings

My data consists of an array filled with objects like this data = [ { mas_name: (...), mas_plan_end: (...) // 'YYYY-MM-DD' eg: '2021-03-19' mas_plan_start: (...) // 'YYYY-MM-DD' eg: '2021-03-19' ... }, { ...

Storing JavaScript variables in a database: A step-by-step guide

For the past few days, I've been working with CakePHP and trying to save a javascript variable into a MySQL database using AJAX (jQuery). Here's the code I've been using: <!-- document javascripts --> <script type="text/javas ...

Mastering the Rejection of Promises in Javascript with Graceful Elegance

One effective pattern using ES2017 async/await involves: async function () { try { var result = await some_promised_value() } catch (err) { console.log(`This block will be processed in a reject() callback with promise patterns, which is far mo ...

Unable to successfully install Appium using the command 'npm install -g appium'

After successfully installing Node on my Mac running Mavericks using the command 'brew install node', I noticed that the npm version is not being shown. $ node -v v0.10.26 $ npm -v -bash: npm: command not found $ npm install -g appium -bash ...

Angular Reactive Forms - Adding Values Dynamically

I have encountered an issue while working with a reactive form. I am able to append text or files from the form in order to make an http post request successfully. However, I am unsure about how to properly append values like dates, booleans, or arrays. a ...