Angular 7 throwing a TS2304 error: Unable to locate the term 'Stripe'

After installing @types/stripe-v3 and including Stripe's javascript file in a script tag within index.html, I expected the Angular compiler to automatically include all files from the @types node modules. According to my research, and after inspecting @types/stripe-v3/index.d.ts, there should be a globally declared variable named Stripe if the file is successfully included by the compiler. Inside index.d.ts

declare var Stripe: stripe.StripeStatic;

In my service file, the code looks like this:

import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class BetalingService {
  stripe = Stripe(environment.stripeKey);

  constructor() { }

}

However, this results in the following error:

error TS2304: Cannot find name 'Stripe'.

Answer №1

To fix the issue, you need to add the @types/stripe-v3 package in the compilerOptions.types array of your tsconfig.app.json file located in the src directory of your Angular project.

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [
      "stripe-v3"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Credit for this solution goes to bjornharvold. You can find more details in this thread.

Answer №2

Angular determines which types to import based on the settings in the TypeScript configuration file, specifically compilerOptions.types and compilerOptions.typeRoots. TS compilerOptions documentation reference

When creating Angular projects using Angular CLI, two TypeScript configuration files are generated by default.

  1. tsconfig.json at the project root
  2. tsconfig.app.json in the /src directory

If both types and typeRoots are not defined, Angular will import all typings from node_modules/@types/*.

If either of them has a value specified, only those types or the ones from the designated location will be imported. For example:

types: ['stripe-v3'] or typeRoots: ['/someDir']
. This means that other installed types in node_modules/@types/* will not be imported.

An empty array indicates that no types will be automatically imported from node_modules/@types. (e.g. types: [] or typeRoots: []).

By default, the value of compilerOptions.types in tsconfig.app.json is an empty array. This explains why Angular does not fetch the installed typings from node_modules/@types/* automatically.

To resolve this: Install the typings using npm install @types/stripe-v3 and update tsconfig.app.json as follows:

  1. Add stripe-v3 to the types array.
...
"compilerOptions": {
   ...
  "types": ['stripe-v3']
}
  1. Alternatively, remove 'types' from 'compilerOptions'

If you opt to add types manually, remember to include any future typings in this array.

Removing types from compilerOptions will result in automatic importing of all future typings by Angular.

Ensure to also check the types and typeRoots settings in tsconfig.js. The same logic applies to relative paths specified in the typeRoots array.

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

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Is there a way to ensure the switch only changes after I have clicked 'ok' to confirm?

Is there a way to ensure that the toggle switch only changes when I click "Ok" in the confirmation box? If I click "Cancel", I would like for nothing to change. This is my HTML code: <mat-card class="result"> <mat-card-content> <h2 c ...

Angular 2 Directive for Ensuring Required Conditions

Is there a way to make form fields required or not based on the value of other fields? The standard RequiredValidator directive doesn't seem to support this, so I've created my own directive: @Directive({ selector: '[myRequired][ngControl ...

Is "await" considered as a reserved word in ReactJS when using TypeScript?

I am trying to implement async await in my code, but I keep getting an error that says await is a reserved word. Here is the snippet of my code: public componentDidMount() { this.startDrag(); } private startDrag = async () => { const eleme ...

Error TS2305: The module "@prisma/client" does not have an export named "User"

Setting up a Gitlab CI for my nestjs project using prisma has been my current challenge. I keep encountering this error when running the pipeline: see image here This is what my .gitlab-ci.yml looks like: image: node:latest stages: - build build: st ...

Dependency injection in Angular is a powerful design pattern that

I recently completed an Angular 2 website, but I've run into some issues that I cannot seem to debug. I've spent the past week trying to find a solution but have had no luck. Below, I've included some snippets of my code. Feel free to ask fo ...

Invoking functions from an array of TypeScript union types

Within my Typescript array, I have two classes: StripeCardModel | StripeBankModel Both of these classes extend StripePaymentModel My goal is to locate a specific class within the array that can potentially contain instances of both classes. Once found ...

Tips for dealing with strong reference cycles in TypeScript?

I have created a tree-like structure in my implementation, consisting of parent and child objects. The parents contain a list of children while the children have references to their parents, facilitating easy navigation through the tree. I am now contempla ...

Angular 7 compile error NG8002: Unable to bind object as it is not recognized as a valid property

Currently working on an Angular 7/8 test App. Encountering a compile error Can't bind 'discounter' since it isn't a known property of 'paDiscountEditor' The HTML where the error is occurring is simple... Below are all the nec ...

How can I only accept one of two specific function signatures in Typescript and reject any others?

Looking for an answer from the community on Typescript, require either of two function signatures In my code, I am handling a callback where I need to either pass an error or leave the first argument as undefined and pass data as the second argument. To ...

What is the reasoning behind Typescript's belief that the symbol 'name' is consistently present?

When working with Typescript, I've noticed that my code is sometimes accepted by the compiler even when I mistakenly write name instead of someObject.name. To test this behavior, I compiled a file with just console.log(name) and surprisingly, the Typ ...

View choices in a dropdown menu

Looking to display a list in a dropdown using Angular. Here's what I've tried: TypeScript: Constructor export class Merchant { constructor( public id: string, public name: string ) {} } Component: import {Merchant} from "../domai ...

typescript ways to exclude enum values

I am working with enums in TypeScript. enum Status { Cancelled = 'cancelled', Completed = 'completed', Created = 'created' } Now, I need to create another enum that includes only the values Completed and Created. enum S ...

Storing a variety of values within a formControl in Angular

I'm currently working on a form that involves managing an array of quantity materials in TypeScript. These materials can be added or removed from an inventory and are displayed in the HTML using ngFor. My goal is to allow the FormControl to accommodat ...

Is there a way to implement Rust's enum variant classes or Kotlin sealed classes in TypeScript?

When working with HTTP responses in TypeScript, I am interested in creating a variant type that can represent different states. In Rust, a similar type can be defined as: enum Response<T> { Empty, Loading, Failure(String), Success(dat ...

Obtain the function's return type without actually executing the function

Consider the following TypeScript function: export const foo = function(){ return { a: 1, b: true, c: 'bar' } }; If I were to import this function into another file: import {foo} from './foobar'; Is there a me ...

Importing Typescript modules by specifying their namespace instead of using a function

I have been working on a project where I needed to generate typings from graphql using the gql2ts library. In the gql-2-ts file, I initially used a namespace import for glob, which resulted in TypeScript showing me an error as intended. I then switched the ...

What is the method for bypassing tests in TypeScript/esrun when utilizing the node native test runner?

I have been utilizing the node test runner for my testing purposes. Within a small demo file, I have included some tests: import { describe, test } from "node:test"; import assert from "node:assert"; describe("thing", () => ...

Angular 8: Bridging the gap between two players with a shared singleton service

I've been working on creating a multiplayer Battleships game, and although the basic functionality is there, I'm struggling to connect two players to the same game. Any assistance would be greatly appreciated! My goal is to create a service that ...

Angular 5 Image Upload - Transfer your images with ease

I am having trouble saving a simple post in firebase, especially with the image included. This is my current service implementation: uploadAndSave(item: any) { let post = { $key: item.key, title: item.title, description: item.description, url: '&a ...