简体   繁体   English

是否有任何 eslint 规则可以防止“对象作为 React 子对象无效”

[英]Are there any eslint rules that could prevent `Objects are not valid as a React child`

I'm writing React with Typescript and, after making a change to my code, I started seeing Objects are not valid as a React child errors.我正在用 Typescript 编写 React,在对我的代码进行更改后,我开始看到Objects are not valid as a React child is Objects are not valid as a React child错误。

I had changed a property from a string to an Optional<string> , so the error totally makes sense since my <div>{property}</div> code was no longer correct.我已将属性从string更改为Optional<string> ,因此该错误完全有道理,因为我的<div>{property}</div>代码不再正确。

So, this is a type error being caught at runtime.因此,这是在运行时捕获的类型错误。

I'm not doing any casting or any other code "tricks" to try to subvert pre-existing type checking;我没有做任何强制转换或任何其他代码“技巧”来试图破坏预先存在的类型检查; I'm just rendering a value that React detects at runtime to be an object.我只是将 React 在运行时检测到的值渲染为一个对象。

It seems to me that an appropriate linting rule or typescript configuration should have been able to capture that property is no a valid React child.在我看来,适当的 linting 规则或打字稿配置应该能够捕获该property不是有效的 React 子项。

Here's a very simple example ( TSPlayground ):这是一个非常简单的示例( TSPlayground ):

type Props = {
    example:{}
};

const Foo = ({example}: Props) => <div>{example}</div>

I would expect an error pointing to the use of example inside the JSX.我预计会出现一个错误,指出在 JSX 中使用example

I've been doing some googling, but I can't find a rule that seems like it would catch this.我一直在做一些谷歌搜索,但我找不到一条似乎能抓住这一点的规则。

Is there one that anyone knows of?有没有人知道的?

As others have mentioned there's no such a feature available right now.正如其他人所提到的,目前没有这样的功能可用。 Furthermore linters are more geared towards styling than capturing compilation errors.此外,linter 更适合样式而不是捕获编译错误。 I don't think what you're asking is possible because example is a dynamic type and setting it to a string makes it a valid JSX node while setting it to an object makes it invalid.我不认为您要问的是可能的,因为example是动态类型并将其设置为字符串使其成为有效的 JSX 节点,而将其设置为对象则使其无效。 Since JS is a dynamic language we cannot know this ahead of time.由于 JS 是一种动态语言,我们无法提前知道这一点。 Typescript helps in this case, but that's a separate type system from eslint rules and as @jonrsharpe has mentioned in the comments there's an issue on typescript repository to add the feature you're requesting (#35622 ). Typescript 在这种情况下有帮助,但这是一个独立于 eslint 规则的类型系统,正如 @jonrsharpe 在评论中提到的那样,typescript 存储库存在一个问题,无法添加您请求的功能(#35622 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM