如何使用带有 JSX/TSX 的 TypeScript 强制转换
How to use a TypeScript cast with JSX/TSX
在 .tsx
文件中转换时,编译器假定它是 JSX,例如:
(<HtmlInputElement> event.target).value
报错
JSX element type 'HtmlInputElement' is not a constructor function for JSX elements
如何在 .tsx
文件中转换 TypeScript?
TypeScript 1.6 中引入了 as
运算符以替换 .tsx
文件中的强制转换,例如:
(event.target as HTMLInputElement).value
TypeScript wiki 解释了 1.6 的变化:
it makes the new as
operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator)
在 .tsx
文件中转换时,编译器假定它是 JSX,例如:
(<HtmlInputElement> event.target).value
报错
JSX element type 'HtmlInputElement' is not a constructor function for JSX elements
如何在 .tsx
文件中转换 TypeScript?
TypeScript 1.6 中引入了 as
运算符以替换 .tsx
文件中的强制转换,例如:
(event.target as HTMLInputElement).value
TypeScript wiki 解释了 1.6 的变化:
it makes the new as
operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator)