【问题标题】:How can I get the interface of an object in typescript?如何在 typescript 中获取对象的接口?
【发布时间】:2020-08-08 03:42:11
【问题描述】:

我正在尝试为我创建一个处理 gmail 的类,问题是我想要该对象的 typescript intellisense。但是,这并没有给我尝试在构造函数中创建的 google 对象的类型:

class Gmail {
    private auth: any;
    google = null;
    messageList: emailListType = ('' as unknown) as emailListType;
    constructor(auth) {
        this.google = google.gmail({ version: 'v1', auth: this.auth }).users;
    }
    async getEmailsInLabel(label: string) {
        //@ts-ignore
        this.messageList = await this.google.messages.list({
            labelIds: [label],
            userId: 'me',
        });
    }
}

我也试过去那个函数的类型定义,发现这个:

import { AuthPlus } from 'googleapis-common';
import { gmail_v1 } from './v1';
export declare const VERSIONS: {
    'v1': typeof gmail_v1.Gmail;
};
export declare function gmail(version: 'v1'): gmail_v1.Gmail;
export declare function gmail(options: gmail_v1.Options): gmail_v1.Gmail;
declare const auth: AuthPlus;
export { auth };

google 对象的类型似乎是 gmail_v1.Gmail,但是每当我尝试导入 gmail_v1.Gmail 界面打字稿时,都会说我无法从 d.ts 文件导入。

我也试过这个:

class Gmail {
        private auth: any;
        google = google.gmail({ version: 'v1', auth: this.auth }).users;
        messageList: emailListType = ('' as unknown) as emailListType;
        constructor(auth) {
            this.auth = auth;
        }
        async getEmailsInLabel(label: string) {
            //@ts-ignore
            this.messageList = await this.google.messages.list({
                labelIds: [label],
                userId: 'me',
            });
        }
    }

适用于键入但不运行该函数但没有实际意义,我还尝试重新分配构造函数内部的 google 属性,使其等于执行 google.gmail 函数:不起作用。

TLDR:如何将我的类中的 google 属性类型设置为 gmail_v1.Gmail 接口的类型?如何从外部库中获取对象的接口?构建这样的类以便构造函数将类型传递给属性的最佳实践是什么?

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    从“../node_modules/googleapis/build/src/apis/gmail/v1”导入{ gmail_v1}; 正在为我工​​作。

    【讨论】:

      【解决方案2】:

      查看the code,您要查找的接口似乎不是由库导出的。如果没有导出,则无法导入。

      您无法导入声明文件 (.d.ts)。编辑器等工具使用它们来验证代码并帮助开发人员。

      【讨论】:

        猜你喜欢
        • 2019-05-17
        • 2020-10-30
        • 2021-07-31
        • 2017-01-10
        • 2021-01-18
        • 2021-06-26
        • 1970-01-01
        • 1970-01-01
        • 2022-01-12
        相关资源
        最近更新 更多