【问题标题】:How to constraint the return type of a function based on JSX?如何约束基于 JSX 的函数的返回类型?
【发布时间】:2021-07-11 20:44:11
【问题描述】:

我想创建一个返回类型应该返回特定 JSX 类型的函数。

例如:

const setHosting : <GitlabLogo> | <GithubLogo> = (h: Hosting) => ???

这里的返回类型应该是&lt;GitlabLogo&gt;&lt;GithubLogo&gt;。有可能吗?

【问题讨论】:

  • 如果你想返回这些exact组件,你应该返回GitlabLogo,而 &lt;GitlabLogo&gt;。如果你想返回后一种形式,并且没有唯一的属性或结果,你唯一的选择是像React.ComponentReact.NodeReact.FunctionComponent这样的通用形式。
  • 我试过const setHosting = (h: Hosting): (GitlabLogo | GithubLogo&gt;) =&gt; 但它不起作用。
  • 您拥有 25K 的声誉,因此您必须知道此时“不起作用”并不是很有帮助 =)。尝试添加一个最小的可重现示例 + 错误输出。

标签: reactjs typescript jsx


【解决方案1】:

简而言之——不,这是不可能的。

如果您希望函数返回 JSX 元素(即&lt;GithubLogo /&gt;),那么您不能要求它是特定类型,因为所有 JSX 元素都只是类型 JSX.Element

如果您希望该函数返回 组件(即GithubLogo),那么您可以做得更好一点,但不会更好。请记住,Typescript 是结构性的,而不是名义上的类型。如果GitlabLogo 是一个不接受任何道具并返回JSX.Element 的函数组件,那么没有道具的任何 函数组件都可以分配给typeof GitlabLogo。所以你不能需要一个特定的组件。您只能要求特定的道具类型。

type Hosting = "gitlab" | "github";

// return an element
const setHostingA = (h: Hosting): JSX.Element => h === "github" ? <GithubLogo/> : <GitlabLogo/>;

// return a component
const setHostingB = (h: Hosting): React.ComponentType<{}> => h === "github" ? GithubLogo : GitlabLogo;
const HostingComponent = setHostingB("github");
const element = <HostingComponent/>

// call as a component - return an element
const HostingLogo = ({hosting}: {hosting: Hosting}): JSX.Element => {
    const Component = hosting === "github" ? GithubLogo : GitlabLogo;
    return <Component/>;
}
const a = <HostingLogo hosting="github"/>;
const b = <HostingLogo hosting="gitlab"/>;

Typescript Playground Link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    相关资源
    最近更新 更多