Typescript TSX and generic parameters

拟墨画扇 提交于 2020-11-30 20:35:18

问题


Typescript introduces support for the JSX syntax. So I have an expression that works quite well with traditional *.ts files but no with *.tsx ones:

const f = <T1>(arg1: T1) => <T2>(arg2: T2) => {
   return { arg1, arg2 };
}

I wonder is there a way to make it work inside a *.tsx file?


回答1:


You could use function expressions instead:

const f = function<T1>(arg1: T1) {
    return function<T2>(arg2: T2) {
        return { arg1, arg2 };
    };
};

Or alternatively, I've discovered this works:

const f = <T1, T2>(arg1: T1) => (arg2: T2) => {
   return { arg1, arg2 };
};

On a sidenote, it seems that it will compile fine when multiple generic parameters are provided, but not one. For example, providing a dummy generic parameter will make this work:

const f = <T1, _>(arg1: T1) => {
   return { arg1 };
};

// or just adding a comma
const g = <T1,>(arg1: T1) => {
   return { arg1 };
};

That's definitely not ideal though. There might be another way to make this work with just one generic parameter, but I'm not sure.




回答2:


This is a result of parsing ambiguity issues. One thing that would make this unambiguous is adding an explicit constraint on T1.

const f = <T1 extends unknown>(arg1: T1) => {
    return { arg1 };
}

Type parameters like T1 implicitly have a constraint of unknown anyway, so in this case your code is functionally equivalent.

Take this solution and you can apply on each arrow function from your original example.



来源:https://stackoverflow.com/questions/32696475/typescript-tsx-and-generic-parameters

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