令人困惑的打字稿通用打字错误

时间:2018-08-31 09:18:55

标签: typescript generics

我真的很困惑。如果您需要任何其他详细信息,这也是this的扩展。

这是我的代码:

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]
    }

    ...
}

在这最后if行上显示以下ts错误:

Type '{ "twitter:tweets"?: Collection<Tweet> | undefined; "twitter:users"?: Collection<User> | undefined; "twitter:metadata-cashtag"?: Collection<CashtagMetadataDb> | undefined; "coins:all"?: Collection<...> | undefined; }[T]' is not assignable to type 'Collection<Collections[T]>'.
    Type 'Collection<Tweet> | Collection<User> | Collection<CashtagMetadataDb> | Collection<Coin> | undefined' is not assignable to type 'Collection<Collections[T]>'.
        Type 'undefined' is not assignable to type 'Collection<Collections[T]>'.

如您所见,我已经尽力在这里键入check,但是我无法使其正常工作。

感谢您的帮助:)

1 个答案:

答案 0 :(得分:1)

自动缩小不适用于_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
    }
    // ...
}
相关问题