[英]How to type narrow JSX.Element
I'd like to have a variable that can be either a React component or a string, like this:我想要一个可以是 React 组件或字符串的变量,如下所示:
function MyComponent(): JSX.Element {
let icon: JSX.Element | string = "/example.png"; // (simplified)
return <div>{typeof icon === "JSX.Element" ? icon : <img src={icon} />}</div>;
}
however TS complains about my condition saying:然而 TS 抱怨我的情况说:
TS2367: This condition will always return 'false' since the types '"string" |
TS2367:此条件将始终返回“false”,因为类型为“string”| "number" |
“数字” | "bigint" |
“双” | "boolean" |
“布尔值” | "symbol" |
“符号” | "undefined" |
“未定义” | "object" |
“对象” | "function"' and '"JSX.Element"' have no overlap.
"function"' 和 '"JSX.Element"' 没有重叠。
What should I do?我应该怎么办?
The typeof
operator cannot return "JSX.Element"
. typeof
运算符不能返回"JSX.Element"
。 It can only return the string types listed in that error message:它只能返回该错误消息中列出的字符串类型:
"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
Which means that you will need to check against something in that list, like "string"
.这意味着您需要检查该列表中的某些内容,例如
"string"
。
function MyComponent(): JSX.Element {
let icon: JSX.Element | string = "/example.png";
return <div>{typeof icon === "string" ? <img src={icon} /> : icon }</div>;
}
The accepted answer is the best for my simplified question.接受的答案最适合我的简化问题。
If for some reason, you do want to type narrow against the element, rather than against string
, apparently you can also use React.isValidElement
, which type narrows.如果出于某种原因,你确实想针对元素键入 narrow,而不是针对
string
,显然你也可以使用React.isValidElement
,它会键入 narrows。
You'd have to change the type JSX.Element
to ReactElement
:您必须将类型
JSX.Element
更改为ReactElement
:
function MyComponent(): JSX.Element {
let icon: ReactElement | string = "/example.png"; // (simplified)
return <div>{React.isValidElement(icon) ? icon : <img src={icon} />}</div>;
}
If changing to JSX.Element
is unacceptable, you could create your own user-defined type guard , which interrogates the object to determine if it is indeed a JSX.Element
(see here ).如果更改为
JSX.Element
是不可接受的,您可以创建自己的用户定义类型保护,它会询问 object 以确定它是否确实是JSX.Element
(请参阅此处)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.