问题
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