首页 > 解决方案 > 打字稿 - 通用约束 - 不接受匹配类型的对象文字

问题描述

在 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。我知道我可以在我的对象文字上进行类型化,这可以解决它,但是我不明白我为什么需要它。打字稿具有查找类型匹配的所有信息。

在这种情况下无法识别的原因是什么?

标签: angulartypescriptgeneric-constraints

解决方案


推荐阅读