如何在Google Ads TypeScript项目中导入@types/google-apps-script类型?
Google Ads Script TypeScript中BigQuery接口类型标注的解决方案
问题背景
用TypeScript开发Google Ads Script项目时,BigQuery是全局作用域的对象,不需要像Node.js那样导入实际库,只需要引入@types/google-apps-script就能消除BigQuery未定义的类型错误。但想导入TableFieldSchema这类接口来标注函数返回值时,用import type {TableFieldSchema} from "@types/google-apps-script"的方式行不通。
解决方法
因为@types/google-apps-script把Google Apps Script的所有类型都声明在全局的GoogleAppsScript命名空间下,所以不需要import,直接通过这个命名空间访问对应的类型即可。
具体操作
- 先确认
tsconfig.json里已经配置了包含google-apps-script类型:
{ "compilerOptions": { "types": ["google-apps-script"] } }
- 直接使用
GoogleAppsScript.BigQuery.TableFieldSchema作为返回类型标注,不需要任何导入语句。
修改后的示例代码
const bqQuerySchemaGenerator = (description: string, name: string, type: string): GoogleAppsScript.BigQuery.TableFieldSchema => { const nameFieldSchema = BigQuery.newTableFieldSchema(); nameFieldSchema.description = description; nameFieldSchema.name = name; nameFieldSchema.type = type; return nameFieldSchema; }
原理说明
@types/google-apps-script是为Google Apps Script的全局运行环境设计的类型声明包,所有接口、类型都挂载在全局的GoogleAppsScript命名空间下,和Node.js的模块式类型系统不同,因此直接通过命名空间访问即可完成类型标注,无需导入操作。
内容的提问来源于stack exchange,提问作者marketergeek
相关产品推荐
相关产品推荐

