如何在打字稿中获取对象的界面?

时间:2020-04-24 14:18:24

标签: node.js typescript

我正在尝试创建一个为我处理gmail的类,问题是我想要该对象的打字稿智能感知。但是,这并不能为我提供要在构造函数中创建的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界面的类型?如何从外部库获取对象的接口?构建此类的最佳方法是什么,以便构造函数将类型传递给属性?

2 个答案:

答案 0 :(得分:0)

the code看,您正在寻找的接口似乎没有被库导出。如果未导出,则无法导入。

您不能导入声明文件(.d.ts)。诸如编辑器之类的工具使用它们来验证代码并帮助开发人员。

答案 1 :(得分:0)

从'../node_modules/googleapis/build/src/apis/gmail/v1'导入{gmail_v1}; 为我工作。