CodexBloom - Programming Q&A Platform

TypeScript Generics with Default Type Parameters in React Functional Component – advanced patterns

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-08-21
typescript react generics TypeScript

I need some guidance on I'm working with an scenario with using TypeScript generics in a React functional component. I'm trying to create a generic button component that accepts a `T` type for the props, but when I set a default type for `T`, I get unexpected type inference. Here's the code I'm working with: ```typescript import React from 'react'; type ButtonProps<T = {}> = { onClick: (data: T) => void; label: string; }; const Button = <T,>({ onClick, label }: ButtonProps<T>) => { return <button onClick={() => onClick({} as T)}>{label}</button>; }; const App: React.FC = () => { const handleClick = (data: { id: number }) => { console.log(data.id); }; return <Button onClick={handleClick} label="Click Me" />; }; export default App; ``` When I try to pass `handleClick` to the `Button` component, I get the following behavior: ``` Argument of type '(data: { id: number; }) => void' is not assignable to parameter of type '(data: {}) => void'. Type '{ id: number; }' is not assignable to type '{}'. ``` I expected TypeScript to infer the `T` type based on the `handleClick` function, but it defaults to `{}`. I’ve tried removing the explicit generic declaration in the `Button` component, but that led to other typing issues when I tried to pass different types. Is there a way to properly handle this in TypeScript to ensure that the type passed to `onClick` is inferred correctly from the function I pass in? I'm using TypeScript 4.5.2 and React 17.0.2. My development environment is Ubuntu. Is there a better approach? I'm using Typescript LTS in this project. What would be the recommended way to handle this? Am I approaching this the right way? This is part of a larger desktop app I'm building.