为什么带泛型参数的函数会打破Typescript推理



我有一个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。为什么会发生这种情况,有没有办法解决这个问题?

您没有指定类型,因此它被推断为unknown,并且没有按预期排列。

必须正确地指定类型,以使其遵循已设置的泛型类型。像这样,

TestWithAs<GenericProps<string>>({
as: GenericComp,
value: "",
options: [""],
genericFunc: (test: string) => {}
})

最新更新