【问题标题】:Extend a Typescript generic with additional data使用附加数据扩展 Typescript 泛型
【发布时间】:2021-01-06 16:51:13
【问题描述】:

我正在尝试使用 Typescript 为 Firestore 收集数据创建一个辅助实用程序。该实用程序应该不知道传入了什么数据,而是将正确的返回类型表达给调用它的任何内容。我不确定如何将我的 Typescript 类型传递给函数并让它正确返回。到目前为止,我所拥有的如下:

interface CollectionWithId<T extends {}> {
  id: string;
}

/**
 * Get all docs from collection `collectionName` optionally
 * @param collectionName
 */
export async function getCollectionDocs<T>(collectionName: string): Promise<CollectionWithId<T>[]> {
  const documentQuery = firebase.firestore().collection(collectionName);
  const documentQuerySnapshot = await documentQuery.get();

  return documentQuerySnapshot.empty
    ? []
    : _map(documentQuerySnapshot.docs, (doc) => ({
        ...doc.data(),
        id: doc.id,
      }));
}

在调用getCollectionDocs&lt;User&gt;() 时,我希望返回的数据能够自动完成用户的所有属性。现在,我只得到id 属性。

Firestore 完成操作后,如何获取我的User 接口的所有属性?

【问题讨论】:

    标签: typescript google-cloud-firestore typescript-generics


    【解决方案1】:

    使用找到的信息here,我做了以下事情:

    type CollectionWithId<T> = T & {
      id: string;
    };
    
    export async function getCollectionDocs<T>(
      collectionName: string,
      limit?: number,
      offset?: number
    ): Promise<CollectionWithId<T>[]> {
      ...
    }
    

    这似乎按预期工作。

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 2018-04-09
      • 2013-09-30
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多