【发布时间】:2021-08-26 13:11:37
【问题描述】:
我有一个 React 组件,它提取和扩展通过 as={Component} 参数传入的组件的 props。下面的例子
type ComponentWithAs = <Props>(props: Props & {
as: React.ComponentType<Props>
}) => any;
let TestWithAs: ComponentWithAs = () => null;
这样工作:
type Props = {
value: string;
options: string[];
genericFunc: (test: string) => void;
};
function Comp(props: Props) { return null };
TestWithAs({
as: Comp,
value: "",
options: [""],
genericFunc: (test) => {}, // works
})
但是,当传递在函数中使用这些泛型的泛型组件时。它只是推断泛型的未知数。
type GenericProps<T> = {
value: T;
options: T[];
genericFunc: (test: T) => void;
};
function GenericComp<T>(props: GenericProps<T>) { return null };
TestWithAs({
as: GenericComp, // does not infer generic
value: "",
options: [""],
genericFunc: (test: string) => {}, // should work but infer's unkown
})
由于某种原因,所有道具都被推断为unkown。为什么会发生这种情况,有没有办法解决这个问题?
【问题讨论】:
标签: typescript typescript-generics