Typescript TSX and general options

Typescript introduces JSX syntax support. Therefore, I have an expression that works well with traditional * .ts files, but not * .tsx:

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

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

+10
source share
2 answers

Instead, you can use function expressions:

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

Or, alternatively, I found that this works:

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

Regarding sidenote, it seems that it will compile normally when several common parameters are provided, but not one. For example, providing a dummy shared parameter will do the job:

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

It is definitely not perfect, though. There may be another way to get this to work with only one common parameter, but I'm not sure.

+8
source

This is the result of parsing ambiguity problems. The only thing that would make it unambiguous is to add an explicit restriction on T1 .

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

Parameters of type T1 implicitly have a restriction {} in any case, so in this case your code is functionally equivalent.

Take this decision, and you can apply arrows to each function in your original example.

+8
source

Source: https://habr.com/ru/post/1231952/


All Articles