【问题标题】:Why does a function with generic argument break Typescript inferrance为什么具有通用参数的函数会破坏 Typescript 推断
【发布时间】: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
})

Playground link

由于某种原因,所有道具都被推断为unkown。为什么会发生这种情况,有没有办法解决这个问题?

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

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

    您必须正确指定类型以使其符合您设置的泛型类型。像这样的,

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

    【讨论】:

    • 我知道它可以通过传递显式类型来工作,但是我问为什么在传入函数时需要它,但在我删除 genericFunc Playground 时不需要它
    • 我不确定我是否遵循。请你详细说明一下。据我所知,它无法根据您的设置方式自动解释事物,您必须再次指定泛型类型才能理解其意图。但我会等待你的澄清,并确保我不会遗漏任何东西。也许您可以编辑问题以添加此工作的用例与这不起作用与您对更简单示例的期望可能是什么,以便我们可以跟进并提供相应的帮助。
    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    相关资源
    最近更新 更多