Alasdair McLeay
Alasdair McLeay

Reputation: 2632

TypeScript - Use a generic type for a function

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.

playground for the above

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

Answers (1)

Shivam Singla
Shivam Singla

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];

[Playground]

Explanation

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

Related Questions