【问题标题】:Importing types from @types without corresponding library从没有相应库的@types 导入类型
【发布时间】:2023-02-24 02:21:45
【问题描述】:

抱歉,如果问题不清楚,但我不知道该怎么说。我有一个使用 Typescript 开发的 Google Ads Script 项目。我使用 BigQuery 库。如您所知,在 Google Ads 中您不需要导入任何库(如在 Node.js 中),因为它们已经在全球范围内可用。

所以我只需要从https://www.npmjs.com/package/@types/google-apps-script导入类型。它的工作方式是取消任何错误,如未定义 BigQuery 等。但是我可以导入和使用任何特定接口吗?

例如,我有一个返回TableFieldSchema 的函数。

const bqQuerySchemaGenerator = (description: string, name: string, type: string) => {
    const nameFieldSchema : any = BigQuery.newTableFieldSchema();
    nameFieldSchema.description = description;
    nameFieldSchema.name = name;
    nameFieldSchema.type = type;
    return nameFieldSchema
}

我想定义一个类型来显示此函数返回的内容。我知道通常如果我使用相应的库我会导入类似

import {TableFieldSchema} from "google-apps-script"

但正如我提到的,我不使用任何外部库,所以我会想象这样的事情

import type {TableFieldSchema} from "@types/google-apps-script"

const bqQuerySchemaGenerator = (description: string, name: string, type: string) : TableFieldSchema => {
    const nameFieldSchema : any = BigQuery.newTableFieldSchema();
    nameFieldSchema.description = description;
    nameFieldSchema.name = name;
    nameFieldSchema.type = type;
    return nameFieldSchema
}

但它不起作用。如何导入这些类型?甚至有可能吗?

【问题讨论】:

    标签: typescript google-ads-script


    【解决方案1】:

    如果您已经安装了您提到的类型包:

    npm install --save-dev @types/google-apps-script
    

    那么你应该能够使用global object上的GoogleAppsScriptnamespace访问类型(没有import语句),就像你可以访问你显示的值一样(例如BigQuery对象):

    const bqQuerySchemaGenerator = (description: string, name: string, type: string): GoogleAppsScript.BigQuery.Schema.TableFieldSchema => {
      const nameFieldSchema = BigQuery.newTableFieldSchema();
      nameFieldSchema.description = description;
      nameFieldSchema.name = name;
      nameFieldSchema.type = type;
      return nameFieldSchema;
    };
    
    

    或者,如果您打算重用它,您也可以为任何类型起别名。这样你就不必每次都输入完整的命名空间路径:

    type TableFieldSchema = GoogleAppsScript.BigQuery.Schema.TableFieldSchema;
    
    const bqQuerySchemaGenerator = (description: string, name: string, type: string): TableFieldSchema => {
      const nameFieldSchema = BigQuery.newTableFieldSchema();
      nameFieldSchema.description = description;
      nameFieldSchema.name = name;
      nameFieldSchema.type = type;
      return nameFieldSchema;
    };
    
    

    【讨论】:

      猜你喜欢
      • 2019-02-06
      • 2017-02-10
      • 2019-06-06
      • 2021-05-22
      • 2017-12-05
      • 2017-05-06
      • 2021-07-21
      • 2014-01-12
      • 1970-01-01
      相关资源
      最近更新 更多