如何为外部库定义类型。打字稿,Angular 和 Google 选择器

How can I define types for external libraries. TypeScript , Angular and Google Picker

我正在尝试在我的 Angular 4 应用程序中使用 Google 选择器 API。 为了能够使用 Google Picker 的功能,我必须导入库,并且在我的 index.html 文件中进行。

index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="theme-color" content="#2185d0">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <title>Librostic</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="https://use.fontawesome.com/18845e1b3c.js"></script>

  <link href="https://fonts.googleapis.com/css?family=Alfa+Slab+One" rel="stylesheet">
</head>
<body>
  <app-root>
  </app-root>
  <!-- See the bellow script -->
  <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script> 
</body>

<script>
  $('.ui.dropdown')
    .dropdown()
  ;
</script>
</html>

所以问题是我尝试使用某些方法的地方,因为 Typescript 不知道那是什么。 让我们看一个例子。 我得到了以下功能:

function createPicker() {
      if (pickerApiLoaded && oauthToken) {
        // Here I get errors like: Cannot find name 'google'.
        var view = new google.picker.View(google.picker.ViewId.DOCS);
        view.setMimeTypes('application/pdf');
        var picker = new google.picker.PickerBuilder()
          .enableFeature(google.picker.Feature.NAV_HIDDEN)
          .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
          .setAppId(appId)
          .setOAuthToken(oauthToken)
          .addView(view)
          .addView(new google.picker.DocsUploadView())
          .setDeveloperKey(developerKey)
          .setCallback(pickerCallback)
          .build();
        picker.setVisible(true);
      }
    }

这只是一个 TypeScript 错误,意味着该函数是在没有 TS 编译器的情况下执行的。我怎么解决这个问题? 谢谢!

有人可能已经为这个库编写了类型。您应该查看 this repo,其中包含许多库的定义。您通常可以使用 npm install @types/<library-name> --save-dev.

安装这些定义

否则,如果还没有定义,而你只是想继续做事,你可以通过将库声明为 any 来使打字稿静音,即文件顶部的 declare const google: any;。但是如果你这样做,你在使用库时会失去所有的类型安全。

扩充 CRice 的答案,

您正在寻找 npm install @types/google.picker @types/gapi.client --save-dev