node.js - 如何自定义firebase DocumentData接口(interface)?

标签 node.js typescript firebase google-cloud-firestore

我正在使用 firebase@5.5.8 和 typescript@3.1.4

每当我从 firestore 创建文档时,我都会按预期获得 firebase.firestore.DocumentReference 类型的对象

如果我调用 get(options?: firebase.firestore.GetOptions|undefined) 我将按预期获得 firebase.firestore.DocumentSnapshot 类型的对象

如果我调用data(options?: firebase.firestore.DataOptions|undefined),我将得到一个 firebase.firestore.DocumentData 对象或 undefined object ,如预期

现在,在我的管理器对象上,我知道我要写入数据库的内容,因此我可以断言,无论您从我的管理器中获得什么 DocumentData,您都将获得如图所示的客户端

export interface Client {
    name: string;
    website?: string;
    description?: string;
    visible: boolean;
}

我想为我的管理器对象创建一个接口(interface)来表达这一点。所以我尝试过:

export interface FirebaseDocumentSnapshot<T> extends $firebase.firestore.DocumentSnapshot {
    data(options?: $firebase.firestore.SnapshotOptions | undefined): T|undefined
}

export interface FirebaseDocumentReference<T> extends $firebase.firestore.DocumentReference {
    get(options?: $firebase.firestore.GetOptions | undefined): Promise<FirebaseDocumentSnapshot<T>>
}

我遇到的问题在这里:

const client: Client = mapClient(args);

const result: FirebaseDocumentReference<Client> = await $db.add(client);

错误是:

[ts]

Type 'DocumentReference' is not assignable to type 'FirebaseDocumentReference<Client>'.
  Types of property 'get' are incompatible.
    Type '(options?: GetOptions | undefined) => Promise<DocumentSnapshot>' is not assignable to type '(options?: GetOptions | undefined) => Promise<FirebaseDocumentSnapshot<Client>>'.
      Type 'Promise<DocumentSnapshot>' is not assignable to type 'Promise<FirebaseDocumentSnapshot<Client>>'.
        Type 'DocumentSnapshot' is not assignable to type 'FirebaseDocumentSnapshot<Client>'.
          Types of property 'data' are incompatible.
            Type '(options?: SnapshotOptions | undefined) => DocumentData | undefined' is not assignable to type '(options?: SnapshotOptions | undefined) => Client | undefined'.
              Type 'DocumentData | undefined' is not assignable to type 'Client | undefined'.
                Type 'DocumentData' is not assignable to type 'Client'.
                  Property 'name' is missing in type 'DocumentData'. [2322]
const result: FirebaseDocumentReference<Client>

如何声明接口(interface)以便知道结果对象的类型?

最佳答案

一个简单的解决方案是转换返回数据:

const client = snapshot.data() 作为客户端

关于node.js - 如何自定义firebase DocumentData接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53674582/

相关文章:

javascript - Nodejs发送基本网页

javascript - 不等待调用异步函数的缺点

typescript - @types - 对象键的值数组

javascript - 使用组节点从多维子数组创建字符串

javascript - 如何从 Google Firebase 中存储的数据创建 JSON 字符串

ios - Firebase 实时数据库名称和值

javascript - 读取文件以在快速路径中使用

angular - 无法解析存储 : (? 的所有参数)

ios - Firebase 的正确数据结构

node.js - 使 Alexa Skill 通过 HTTP 正常工作从 JSON 文件说话