How to use generics with arrow functions in Typescript/JSX with React?

烈酒焚心 提交于 2019-12-04 05:48:48

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.

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();

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 {}.

I can't think of a way around that, and will be glad as you to learn of one.
However, here's a different way to achieve the same:

export const foo = function<T>(myObject: T) { return myObject.toString(); }

The compiler won't complain about the generics.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!