angular - 打字稿 - 通用约束 - 不接受匹配类型的对象文字
问题描述
在 angular 7 框架中使用 typescript 3。
我正在尝试为 firebase 准备我的本地 Store 数组元素,使用对象的 Id 属性作为包装对象中的关键,反之亦然。
我已经设置了一个可以与我的任何本地 Store 元素一起使用的接口,因为它们都有一个 id 属性:
interface localItem {id:string, [x:string]:any}
和 firebase 等价物,因为它们都使用 id 作为键
interface firebaseItem {[id:string]:{[x:string]:any}}
我正在尝试迭代 firebase 项目,并将其再次转换为数组,但出现类型错误:
unwrapForLocalStore<T extends localItem>(firebaseItems:firebaseItem):T[]{
let itemArray: T[] = [];
for(let item in firebaseItems){
let newItem:T = {id:item, ...firebaseItems[item]}
/*
[ts] Type '{ id: string; }' is not assignable to type 'T'. [2322]
let newItem: T extends localItem
*/
itemArray.push(newItem)
}
return itemArray
}
我已经阅读了打字稿文档,除非我遗漏了一些东西,否则我不明白为什么我创建的对象文字不能分配给类型 T。我知道我可以在我的对象文字上进行类型化,这可以解决它,但是我不明白我为什么需要它。打字稿具有查找类型匹配的所有信息。
在这种情况下无法识别的原因是什么?
解决方案
推荐阅读
- c - 退出代码 11 - 如何修复它
- r - Sekhon 从 R 中的 Matching 包中获取匹配的数据集
- reactjs - 如何使用带有 React Hooks 的 setState 从 local.storage 设置 JSON 对象
- excel - 形状和文本框无法在单元格中正确打印
- swift - 我可以将按钮连接到 xcode 中新的 swift 文件中的结构吗?
- python - 初学者python游戏:掷骰子,while循环问题
- python - 变量自动赋值和递增
- aws-sdk - AWS IoT 连接错误:aws-iot-device-sdk 提供的“caCert”选项无效
- python - 如何从 ffprobe 设置变量
- wordpress - ACF 前端字段复选框:标记为已读