【问题标题】:Is it possible to prevent JSX comment from adding a 'children' element, potentially breaking types?是否可以防止 JSX 注释添加“子”元素,从而可能破坏类型?
【发布时间】:2020-11-03 17:37:19
【问题描述】:

假设我有一个这样的第三方库:

declare var SomeComponentFromLibrary: React.FC<{
    children?: React.ReactElement
}>;

children 被定义为React.ReactElement,我无法改变这一事实。

现在,假设我使用它,其中一个组件 &lt;MyComponent /&gt; 恰好产生了一个类型错误,我希望暂时抑制该错误:

<SomeComponentFromLibrary>
    {/* @ts-expect-error */}
    <MyComponent />
</SomeComponentFromLibrary>

这会在 SomeComponentFromLibrarychildren 中创建 2 个项目(注释 {}&lt;MyComponent),而 SomeComponentFromLibrary 的类型定义只需要一个孩子,从而产生:

Type '{ children: any[]; }' is not assignable to type '{ children?: ReactElement.... }'.

是否有可能在 ~~JSX 中使用 typescript @ts- cmets(嗯,或任何其他 cmets)而不创建实际的孩子?~~

编辑:

看起来当我添加评论时,它并没有改变生成的 JavaScript ((React.createElement(SomeComponentFromLibrary, null, React.createElement(MyComponent, null)))) -- 但由于某种原因,TypeScript 仍然抱怨(childrenany[])。我认为这可能是 TS 中的一个错误——也许它解析 JSX 的方式不同?

【问题讨论】:

  • {null/*comment*/}React.ReactElement[],很确定你不能以其他方式解决这个问题:-(
  • 据我所知,{/*...*/} 对发送到组件的内容没有任何影响:jsfiddle.net/tjcrowder/qLspfmxc 例如,它不会让您的组件中有多个孩子例子。有一个孩子:&lt;MyComponent /&gt;。 (我必须尝试一下才能确定。:-))
  • @T.J.Crowder,啊,你是对的!我得到export default () =&gt; (React.createElement(SomeComponentFromLibrary, null, React.createElement(MyComponent, null))); 没有额外的孩子被传递!那么这一定是 TS 问题,而不是 JSX -> JS 编译?
  • 如果您确实因此而收到错误,是的,这似乎是一个错误或他们尚未实现的功能。 (我可以发誓 {/*...*/} 以前在 JSX 中不工作——过去的表达式 have 有一个值——但它最近工作了,所以......)你会想要仔细检查您是否完全了解 TS。 :-)

标签: javascript reactjs typescript jsx


【解决方案1】:

遗憾的是,Typescript 注释指令对 JSX 不太友好。但你绝对可以让它发挥作用。

给它一个孩子,用括号括起来,{ },用括号括起来。

<SomeComponentFromLibrary>
    {/* @ts-expect-error */
        <MyComponent />
    }
</SomeComponentFromLibrary>

Playground


另外,附注:SomeComponentFromLibrary 的输入可能只是错误。在我见过的几乎所有情况下,children 都应该输入为React.ReactNode。当你这样输入这个函数时,它now works exactly like you expect.

所以我可能会为这个库创建一个拉取请求来解决这个问题。

【讨论】:

    【解决方案2】:

    看起来这是一个错误:https://github.com/microsoft/TypeScript/issues/41125

    这里已修复:https://github.com/microsoft/TypeScript/pull/41166,应该在 4.1 或 4.2 中发布

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 2017-05-31
      • 1970-01-01
      • 2020-02-29
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      相关资源
      最近更新 更多