如何在带有React的Typescript/JSX中将泛型与箭头功能一起使用? [英] How to use generics with arrow functions in Typescript/JSX with React?
问题描述
使用Typescript在Visual Studio中键入".ts"文件,请考虑以下声明:
Using Typescript, typing in Visual Studio, into a ".ts" file, consider the following declaration:
export const foo = <T>(myObject: T) => myObject.toString();
这很好,类型检查很好,一切都很好.
This works fine, type checking is fine, everything is great.
现在将完全相同的代码放入用于JSX和React的".tsx"文件中.
Now place that exact same code into a ".tsx" file that is being used for JSX and React.
Intellisense感到非常沮丧和抱怨,因为它试图使< T>成为React JSX元素.但是我的目的是让编译器将其视为通用类型指示符.
Intellisense gets very upset and complains, because it is trying to make the <T> into a React JSX element. But my intention is to have the compiler treat it as a generic type designator.
编译器抱怨:
[gulp-typescript] 17008 JSX元素"T"没有相应的结束标记.
[gulp-typescript] 17008 JSX element 'T' has no corresponding closing tag.
我已经尝试了多种语法变通办法来尝试使IDE和编译器都可以让我逃脱JSX并迫使< T>被编译器理解为通用类,就像JSX不存在时一样.使用.但是我找不到神奇的调味料.
I have tried numerous syntactical workarounds to try to get both the IDE and the compiler to let me escape the JSX and force the <T> to be understood by the compiler as a generic, as it would if JSX is not in use. But I can't find the magic sauce to do this.
有谁比我聪明,谁能弄清楚这一点?
Anyone smarter than I out there who can figure this out?
推荐答案
当您拥有单个类型参数时,TypeScript不确定它是否可能是JSX开头标记.它必须选择一个,所以它与JSX一起使用.
When you have a single type parameter, TypeScript isn't sure whether it might be a JSX opening tag or not. It has to choose one, so it goes with JSX.
如果要使用具有完全相同语义的函数,则可以显式列出T
的约束:
If you want a function with the exact same semantics, you can explicitly list the constraint of T
:
const foo = <T extends {}>(myObject: T) => myObject.toString();
这打破了TypeScript的歧义,因此您可以使用通用类型参数.它也具有相同的语义,因为类型参数始终具有{}
的隐式约束.
This breaks the ambiguity for TypeScript so that you can use a generic type parameter. It also has the same semantics because type parameters always have an implicit constraint of {}
.
这篇关于如何在带有React的Typescript/JSX中将泛型与箭头功能一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!