我有以下代码:
type XType<T> = {
x: T;
};
function extractTypes<Props, T>(Component: React.FC<Props & XType<T>>) {
return (props: Props, value: T) => {
Component({ ...props, x: value });
};
}
const CompA: React.FC<{ a: string } & XType<string>> = () => <div>HELLO</div>;
const CompB: React.FC<{ b: string } & XType<number>> = () => <div>WORLD</div>;
extractTypes<{ a: string }, string>(CompA)({ a: 'A' }, 'X'); // OK
extractTypes<{ b: string }, number>(CompB)({ b: 'B' }, 1); // OK
extractTypes(CompA)({ a: 'A' }, 'X'); // Compile error
extractTypes(CompB)({ b: 'B' }, 1); // Compile error
CompA
和CompB
预期a
和b
属性以及XType
中的所有属性.
倒数第三行和倒数第四行编译正确,但TypeScrip编译器在最后两行报告如下:
Argument of type '{ a: string; }' is not assignable to parameter of type 'PropsA & XType<string>'.
Property 'x' is missing in type '{ a: string; }' but required in type 'XType<string>'.ts(2345)
Argument of type '{ b: string; }' is not assignable to parameter of type '{ b: string; } & XType<number>'.
Property 'x' is missing in type '{ b: string; }' but required in type 'XType<number>'.ts(2345)
我try 了许多方法,以确保我可以在不显式指定类型的情况下调用extractTypes
,并且仍然确保该函数返回的方法只接受{ a: string }
或{ b: string }
,而不是{ a: string; x: string }
或{ b: string; x: number }
,但都无济于事.
有没有什么方法可以在不要求显式指定extractTypes
的泛型类型的情况下实现这一点?
我想我需要找到一种方法,通过从一个类型(XType
)中减go 另一个类型(Props
)来创建一个类型.我试过打Omit<Props, keyof XType<T>>
,但在这里打不通.
谢谢!
ASIM