【发布时间】:2020-10-02 00:39:58
【问题描述】:
我有一个带有固定键和动态键的实体/接口。
type FooType = {
id: string;
name: string;
age: number;
createdAt: Timestamp;
} & {[id: string]: number; }
当我从 Cloud Firestore 中提取这些数据时,我想将其转换为包含文档 ID 的数组。
function snapshotAsArray<T>(snap): T[] {
return snapshot
.docs
.map((doc): T => ({ id: doc.id, ...doc.data() }));
}
function getFoo(): Promise<FooType[]> {
return admin.firestore()
.collection('foo')
.get()
.then((snapshot) => snapshotAsArray<FooType>(snapshot));
}
我想让snapshotAsArray() 通用/可重用,但我收到以下错误。
Type '{ id: string; }' is not assignable to type 'T'.
'{ id: string; }' is assignable to the constraint of type 'T',
but 'T' could be instantiated with a different subtype of constraint '{}'.
我可以让通用T 必须始终具有id 属性吗?
【问题讨论】:
-
也许强制转换是解决问题的错误方法,将
doc.data()强制转换为 T 至少没有错误。 -
也与组合类型数据接口?这应该是错误的。
type更适合这个,而不是接口;或者由接口和对象组成的类型。 -
...疲劳。在我的示例中,它应该是类型而不是接口。我已经更新了这个问题。谢谢。
标签: typescript google-cloud-firestore typescript-generics