[英]Type 'Element' is not assignable to type 'string'.ts(2322)
I'm new react typescript developer, here i have a code which works in 'js' 'but when changed to 'tsx' getting error: Type 'Element' is not assignable to type 'string'.ts(2322) it is pointing to 'helperTextt' error (did not find answer else where) should i do: let helperTextt:any = "";我是新的 React typescript 开发人员,这里我有一个在“js”中工作的代码,但是当更改为“tsx”时出现错误:类型“Element”不可分配给类型“string”.ts(2322) 它指向到 'helperTextt' 错误(在其他地方找不到答案)我应该怎么做:让 helperTextt:any = ""; ? ?
any suggestions?有什么建议么?
let helperTextt = ""; if (event.target.id === "hostname") { if (.HOSTNAME_REGEX.test(event.target.value)) { helperTextt = ( <Trans i18nKey="form.formData;hostNameError"> Invalid Host name </Trans> ); errorr = true; } }
You could do你可以做
import { ReactElement } from "react";
and then接着
let helperTextt: ReactElement | null = null;
Typescript is automatically inferring helperTextt
to be a string, if you are certain of its values you can get around this (although it is not preferred to declare type any) by declaring it as type any: Typescript 会自动推断helperTextt
是一个字符串,如果您确定它的值,您可以通过将其声明为 type any 来解决这个问题(尽管不推荐声明 type any):
let helperTextt:any;
you can add type to your helperTextt
variable您可以将类型添加到您的helperTextt
变量
let helperTextt: JSX.Element = null;
let helperText: JSX.Element | string = "";
if (event.target.id === "hostname") {
if (!HOSTNAME_REGEX.test(event.target.value)) {
helperText = (
<Trans i18nKey="form.formData.hostNameError">
Invalid Host name
</Trans>
);
errorr = true;
}
}
Maybe it's an issue related to the inferred type of a variable by Typescript itself, as in my case, I was using title
as the name which was initially a string prop to a Component, but later declared it's type to ReactElement
which gave this issue, Well, to fix this, I just renamed the prop from title
to appTitle
and that worked like magic!也许这是一个与 Typescript 本身推断的变量类型有关的问题,就我而言,我使用title
作为名称,它最初是组件的字符串 prop,但后来声明它是ReactElement
的类型,这导致了这个问题,好吧,为了解决这个问题,我只是将 prop 从title
重命名为appTitle
,这就像变魔术一样有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.