首页 > 解决方案 > 使用附加数据扩展 Typescript 泛型

问题描述

我正在尝试使用 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<User>()时,我希望返回的数据能够自动完成用户的所有属性。现在,我只得到id财产。

在此处输入图像描述

UserFirestore 完成操作后,如何获取界面的所有属性?

标签: typescriptgoogle-cloud-firestoretypescript-generics

解决方案


使用在此处找到的信息,我执行了以下操作:

type CollectionWithId<T> = T & {
  id: string;
};

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

这似乎按预期工作。

在此处输入图像描述


推荐阅读