打字稿泛型类型转换错误

Typescript generic type cast error

我有一个实用函数可以帮助键入检查反应组件中注入的商店

import { Diff } from 'typelevel-ts';
import * as React from 'react';

export type TypedInject<Stores> = <StoreKeyToInject extends keyof 
 Stores>(
 ...storeKeysToInject: StoreKeyToInject[]
 ) => <ExpectedProps extends Pick<Stores, StoreKeyToInject>>(
  component: React.ComponentType<ExpectedProps>
 ) => React.ComponentType<Diff<ExpectedProps, Pick<Stores, 
  StoreKeyToInject>>>;

我收到错误消息“类型 'Pick' 不满足约束条件 'keyof ExpectedProps'。 类型 'Pick' 不可分配给类型 'StoreKeyToInject'。"

能否解释一下它的作用以及如何修复它?

虽然您没有提供使用示例,但根据我对您代码的了解,您想要 return 一个新组件,它不会包含传入的商店 storeKeysToInject .

Pick 从类型中选取属性,因此 Pick<Stores, StoreKeyToInject> 是一个仅包含传递给 storeKeysToInject.

的存储的对象

Diff 从类型中删除键,因此第二个参数必须是要删除的键。所以结论是你真的不需要 Pick 你只需要从 ExpectedProps 中删除 StoreKeyToInjectStoreKeyToInject 已经是 Stores 的关键所以就不用再把Stores带进来讨论了)

export type TypedInject<Stores> = 
    <StoreKeyToInject extends keyof Stores>(...storeKeysToInject: StoreKeyToInject[]) 
        => <ExpectedProps extends Pick<Stores, StoreKeyToInject>> (component: React.ComponentType<ExpectedProps>) 
            => React.ComponentType<Diff<ExpectedProps, StoreKeyToInject>>;