Generics in TypeScript: Arrow Functions vs Normal Functions

As a frontend developer working with TypeScript, you’ve likely used generics to write reusable and type-safe functions. But when switching between arrow functions and normal function declarations, there’s a tiny syntax quirk that trips up many devs—especially in .tsx files.

Let’s break it down 👇

✅ Using Generics in a Normal Function

function convertToArray<T>(value: T): T[] {
  return [value];
}

Nothing strange here. TypeScript understands this as a generic function that wraps the value in an array. Clean, readable, and common.

✅ Using Generics in an Arrow Function

const convertToArray = <T,>(value: T): T[] => {
  return [value];
}

Wait… what’s that comma after <T,>? 🤔

💡 What’s with the Comma?

If you’re working in a .tsx file, the following will throw a syntax error:

// ❌ This will cause an error in TSX files
const convertToArray = <T>(value: T): T[] => [value];

That’s because TypeScript (in .tsx) thinks you’re writing a JSX element. For example:

<MyComponent>(value) => ...

To avoid this confusion, we add a comma after the generic:

// ✅ Now TypeScript knows it's a generic, not JSX
const convertToArray = <T,>(value: T): T[] => [value];

The comma tells the parser:

“Hey TypeScript, I’m declaring a generic function here, not writing JSX.”

🧠 Summary

Feature Normal Function Arrow Function
Generic Syntax <T> <T,> (to avoid JSX issue)
Works in .ts files
Works in .tsx files Only with <T,>
JSX Parsing Ambiguity

 

🧪 TL;DR

  • Both function styles use generics in the same way.

  • The only difference is that arrow functions need <T,> in .tsx to avoid JSX confusion.

  • It’s a syntax hack, not a TypeScript feature.

Leave a Reply

Your email address will not be published. Required fields are marked *