混淆Typescript泛型键入错误

混淆Typescript泛型键入错误,typescript,generics,Typescript,Generics,我真的很困惑。如果您需要任何额外的细节,这也是的扩展 这是我的代码: interface Collections extends Twitter.Collections, Coin.Collections {} type CollectionName = keyof Collections type CollectionType <T extends CollectionName> = Collections[T] const _collections: { [K in C

我真的很困惑。如果您需要任何额外的细节,这也是的扩展

这是我的代码:

interface Collections extends Twitter.Collections, Coin.Collections {}
type CollectionName = keyof Collections
type CollectionType <T extends CollectionName> = Collections[T]

const _collections: {
    [K in CollectionName]?: Collection<CollectionType<K>>
} = {}

export async function getCollection<T extends CollectionName> (name: T): Promise<Collection<CollectionType<T>>> {
    if (name in _collections && typeof _collections[name] !== 'undefined') {
        return _collections[name]
    }

    ...
}
正如你所看到的,我已经尽了最大的努力在这里进行打字检查,但我无法让它工作


感谢您的帮助:)

自动缩小在
\u collections[name]
之类的元素访问表达式上不起作用。如果您想利用缩小的优势,您必须在测试它之前将值保存在局部变量中。由于TypeScript如何解释查找类型的限制,您需要在该局部变量上添加类型注释。这应该起作用:

export async function getCollection<T extends CollectionName>(name: T): Promise<Collection<CollectionType<T>>> {
    let coll: Collection<CollectionType<T>> | undefined = _collections[name];
    if (coll !== undefined) {
        return coll
    }
    // ...
}
导出异步函数getCollection(名称:T):Promise{ let coll:Collection | undefined=_collections[name]; 如果(coll!==未定义){ 返回科尔 } // ... }
提供的代码不足以重现错误。但我认为这与
[K in CollectionName]?
是可选的有关。可以使用明确的断言
return\u collections[name]来修复它
(注意感叹号),但我还是不确定,因为提供的代码不够,我不知道您在
if
子句之后是否返回了正确的类型。因此,当我删除
[K in CollectionName]?
中的
时,这可能是另一个错误。该错误会消失,但我无法在声明中填充对象。我得用砰的一声,
,这是我以前不知道的。谢谢你的帮助:)你能收集完整的代码来重现问题中的错误,这样我就可以调试了吗?
export async function getCollection<T extends CollectionName>(name: T): Promise<Collection<CollectionType<T>>> {
    let coll: Collection<CollectionType<T>> | undefined = _collections[name];
    if (coll !== undefined) {
        return coll
    }
    // ...
}