Reputation: 2632
If I have a function:
const flip = (A, B) => [B, A]
Add types to it:
const flip: <T1, T2>(A: T1, B: T2) => [T2, T1]
= <T1, T2>(A: T1, B: T2) => [B, A];
Then extract the type:
type FlipFunction<T1, T2> = (A: T1, B: T2) => [T2, T1];
How can I use this type for an arrow function (function expression)?
Unfortunately this errors:
export const flip: FlipFunction<T1, T2>
= <T1, T2>(A: T1, B: T2) => [B, A];
Cannot find name 'T1'.
As does this:
export const flip: <T1, T2>FlipFunction<T1, T2>
= <T1, T2>(A: T1, B: T2) => [B, A];
(' expected.
Using a function declaration unfortunately doesn't seem to be an option:
https://github.com/microsoft/TypeScript/issues/22063
edit: for the problem I'm trying to solve, the type FlipFunction
above is already defined, but as an interface, that I can't change
e.g.
interface Component<C,T> extends ComponentBase<ComponentProps<C,T>>
Upvotes: 0
Views: 117
Reputation: 2201
If you want the flip
to be a generic function, do this instead-
type FlipFunction = <T1, T2>(A: T1, B: T2) => [T2, T1];
export const flip2: FlipFunction = <T1, T2>(A: T1, B: T2) => [B, A];
When you are declaring FlipFunction
as type FlipFunction<T1, T2> = (A: T1, B: T2) => [T2, T1];
, it means you need to provide the concrete types for T1
and T2
while declaring the variable of type FlipFunction
.
Taking a simpler example-
type MyType<T> = T
const myVar: MyType<string> = "lorem";
Here the type of myVar
is string
which we provided as concrete type in place of the generic T
.
Upvotes: 3