Angular 7和Stripe错误TS2304:找不到名称“ Stripe”

Rob*_*per 6 stripe-payments typescript definitelytyped angular-cli angular-cli-v7

我已经@types/stripe-v3在中的脚本标签中安装了Stripe的javascript文件,并将其包括在内index.html。假定Angular编译器应自动包含@types节点模块中的所有文件。@types/stripe-v3/index.d.ts如果编译器包含该文件,则在Internet上阅读并查看是否有全局声明的var Stripe。从index.d.ts

declare var Stripe: stripe.StripeStatic;
Run Code Online (Sandbox Code Playgroud)

在我的服务文件中,我有以下代码:

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

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

  constructor() { }

}
Run Code Online (Sandbox Code Playgroud)

导致以下错误:

error TS2304: Cannot find name 'Stripe'.
Run Code Online (Sandbox Code Playgroud)

Rob*_*per 9

通过在Angular项目的目录中的文件数组中包含对该@types/stripe-v3包的引用,可以解决此问题。compilerOptions.typestsconfig.app.jsonsrc

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [
      "stripe-v3"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

此解决方案由bjornharvold此主题中发布

  • 就我而言,我使用的是@ types / stripe-checkout。我遇到了同样的问题,并且向`types`数组添加`stripe-checkout`无效。相反,我在数组中添加了@ types / stripe-checkout来解决问题。希望这可以帮助其他人。 (2认同)

Kri*_*vin 7

Angular 根据打字稿配置文件的值compilerOptions.typescompilerOptions.typeRoots来自打字稿配置文件的值导入类型。 TS compilerOptions 文档参考

默认情况下,使用 angular cli 创建的 Angular 项目将有两个打字稿配置文件。

  1. tsconfig.json 在项目的根目录
  2. tsconfig.app.json/src目录中

如果typestypeRoots都未定义 angular 将从node_modules/@types/*.

但是,如果其中任何一个具有任何值,则只会导入指定的类型或来自指定位置的类型。例如:types: ['stripe-v3'] or typeRoots: ['/someDir']。因此,node_modules/@types/*不会导入所有其他已安装的类型。

如果设置了空数组,则不会自动从node_modules/@types. types: [] or typeRoots: [].

默认情况下compilerOptions.typesintsconfig.app.json将有一个空数组作为其值。这就是 angular 不会node_modules/@types/*自动获取已安装类型的原因。

解决这个问题:npm install @types/stripe-v3打字和输入tsconfig.app.json

  1. 要么添加stripe-v3types.
...
"compilerOptions": {
   ...
  "types": ['stripe-v3']
}
Run Code Online (Sandbox Code Playgroud)
  1. 或者从 compilerOptions 中删除类型

如果添加,则必须将所有未来的类型添加到此数组中。

相反,如果您typescompilerOptionsangular 中删除,则会自动导入所有未来的类型。

还要确保检查typestypeRootstsconfig.jstypeRoots将有相对路径作为数组,同样的逻辑也适用于此。