DeveloperBreeze

Typescript Optimization Development Tutorials, Guides & Insights

Unlock 1+ expert-curated typescript optimization tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your typescript optimization skills on DeveloperBreeze.

Optimizing TypeScript Code with Advanced Type Manipulation and Generics

Tutorial September 02, 2024
typescript

import React from "react";

type FormFieldProps<T> = {
  value: T;
  onChange: (value: T) => void;
};

function FormField<T>({ value, onChange }: FormFieldProps<T>) {
  return (
    <input
      type="text"
      value={String(value)}
      onChange={(e) => onChange(e.target.value as unknown as T)}
    />
  );
}

// Usage
const App = () => {
  const [name, setName] = React.useState<string>("");
  const [age, setAge] = React.useState<number>(0);

  return (
    <div>
      <FormField value={name} onChange={setName} />
      <FormField value={age} onChange={setAge} />
    </div>
  );
};

export default App;

To ensure that our FormField component only works with certain types, we can add type constraints.