Search⌘ K
AI Features

Crafting a Generic Sort Function

Explore how to build a reusable generic sort function in TypeScript and integrate it into a React component. Understand using keyof with generics to access properties for sorting, enabling flexible and type-safe data management in your UI.

What does sort look like?

To get started with our genericSort, let’s think about what sort might look like when it’s used in our component. For example, when we’re rendering the widgets, we can imagine using our genericSort function like this:

JavaScript (JSX)
<h2>Widgets:</h2>
{widgets
.sort((a, b) => genericSort(a, b, "title"))
}

First, we call JavaScript’s built-in ...