简体   繁体   English

TypeScript:字符“>”在 JSX 元素内无效

[英]TypeScript: The character ">" is not valid inside a JSX element

In this code:在这段代码中:

export const createCategoriesParams = (filters: string[]) => {
  const tags = [...filters].filter(i => i !== 'All');
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
  let row = <any>[];

  tags.forEach(item => {
    row.push(`tag=${item}`);
  });

  return row.join('&');
};

when I run my esbuild script, it throws error in:当我运行我的 esbuild 脚本时,它会引发错误:

tags.forEach((item, ind) => {

saying

The character ">" is not valid inside a JSX element字符“>”在 JSX 元素中无效

any idea why this could be happening?知道为什么会这样吗?

The TypeScript handbook warns : TypeScript 手册警告

Recall how to write a type assertion:回想一下如何编写类型断言:

 const foo = <foo>bar;

This asserts the variable bar to have the type foo .这断言变量bar的类型为foo Since TypeScript also uses angle brackets for type assertions, combining it with JSX's syntax would introduce certain parsing difficulties.由于 TypeScript 也使用尖括号进行类型断言,将其与 JSX 的语法结合起来会带来一定的解析困难。 As a result, TypeScript disallows angle bracket type assertions in .tsx files.因此,TypeScript 不允许在.tsx文件中使用尖括号类型断言。

Since the above syntax cannot be used in .tsx files, an alternate type assertion operator should be used: as .由于上述语法不能在.tsx文件中使用,因此应使用备用类型断言运算符: as The example can easily be rewritten with the as operator.这个例子可以很容易地用as操作符重写。

 const foo = bar as foo;

In your case, the line at fault is let row = <any>[];在您的情况下,故障线是let row = <any>[]; which, taken literally, should be written as let row = [] as any;从字面上看,应该写成let row = [] as any; . . Though let row: string[] = [];虽然let row: string[] = []; would be preferable to either.会比任何一个都好。

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

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