15

我已经安装@types/stripe-v3并将 Stripe 的 javascript 文件包含在index.html. 假设 Angular 编译器应该自动包含来自 @types 节点模块的所有文件。@types/stripe-v3/index.d.ts如果编译器包含该文件,则在互联网上阅读并查看应该有一个全局声明的 var Stripe。从index.d.ts

declare var Stripe: stripe.StripeStatic;

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

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

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

  constructor() { }

}

导致以下错误:

error TS2304: Cannot find name 'Stripe'.
4

2 回答 2

28

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

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

此解决方案由bjornharvold此线程中发布。

于 2019-02-18T18:43:06.303 回答
8

Angular 基于 typescript 配置文件的值compilerOptions.typescompilerOptions.typeRoots来自 typescript 配置文件的值导入类型。 TS compilerOptions 文档参考

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

  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.types, intsconfig.app.json将有一个空数组作为其值。这就是为什么 Angular 不能node_modules/@types/*自动获取已安装的类型的原因。

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

  1. 要么添加stripe-v3types.
...
"compilerOptions": {
   ...
  "types": ['stripe-v3']
}
  1. 或者从 compilerOptions 中删除类型

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

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

还要确保检查types和也 typeRoots。将具有作为数组的相对路径,并且相同的逻辑也适用于此处。tsconfig.jstypeRoots

于 2019-09-06T15:00:55.043 回答