DeveloperBreeze

Generics Development Tutorials, Guides & Insights

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

Optimizing TypeScript Code with Advanced Type Manipulation and Generics

Tutorial September 02, 2024
typescript

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

type FormFieldProps<T extends string | number> = {
  value: T;
  onChange: (value: T) => void;
};

TypeScript Generics and Advanced Types Cheatsheet: Master Complex Type Systems

Cheatsheet August 20, 2024
typescript

function identity<T>(arg: T): T {
  return arg;
}

const num = identity<number>(42); // T is replaced with number
const str = identity<string>('Hello'); // T is replaced with string

In this example, T is a type variable that allows the identity function to accept and return any type.

Advanced TypeScript: Type Inference and Advanced Types

Tutorial August 05, 2024
typescript

type IsString<T> = T extends string ? 'string' : 'not string';

type Test1 = IsString<string>; // 'string'
type Test2 = IsString<number>; // 'not string'
type Action = 'create' | 'update' | 'delete';
type Entity = 'user' | 'post';

type LogMessage = `${Action}_${Entity}`;

function logAction(action: LogMessage) {
  console.log(`Logging action: ${action}`);
}

logAction('create_user'); // valid
logAction('update_post'); // valid
// logAction('read_user'); // error