typescript - 使用附加数据扩展 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
财产。
User
Firestore 完成操作后,如何获取界面的所有属性?
解决方案
使用在此处找到的信息,我执行了以下操作:
type CollectionWithId<T> = T & {
id: string;
};
export async function getCollectionDocs<T>(
collectionName: string,
limit?: number,
offset?: number
): Promise<CollectionWithId<T>[]> {
...
}
这似乎按预期工作。
推荐阅读
- visual-studio-code - 如何在 Rider 中设置 VS Code 配色方案?
- java - 序列化 XStream 上的静态嵌套类成员
- ansible - Ansible 一直想成为 root
- jquery - Jquery / Datatable - 悬停列值时如何缩短和显示工具提示?
- java - Java swing,更改 java swing 窗口但出现空白屏幕。单独运行每个程序时,每个程序都可以正常工作
- java - Android 响应:java.nio.charset.UnsupportedCharsetException:utf8mb4
- excel - 需要一系列单元格的公式 - 根据另一个单元格范围中是否存在值来突出显示单元格
- node.js - Eslint plugin import throws "import/no-unresolved" on specific modules inside a Lerna package
- c# - 基于相同 ID 过滤数据
- php - Composer 更新:缺少请求的 PHP 扩展 ext-http