0
0
Typescriptprogramming~5 mins

How TypeScript infers generic types

Choose your learning style9 modes available
Introduction

TypeScript guesses the types you want when you use generic functions or classes. This helps you write less code and catch mistakes early.

When you write a function that works with many types but you want TypeScript to know the exact type each time.
When you want to create reusable components that adapt to different data types automatically.
When you want to avoid writing the type explicitly every time you call a generic function.
When you want TypeScript to check your code for type errors based on the values you use.
Syntax
Typescript
function example<T>(arg: T): T {
  return arg;
}

T is a placeholder for any type you want to use.

TypeScript tries to figure out T from the argument you pass.

Examples
TypeScript infers T as number because 42 is a number.
Typescript
function identity<T>(value: T): T {
  return value;
}

const num = identity(42);
TypeScript infers T as string because 'hello' is a string.
Typescript
function wrapInArray<T>(item: T): T[] {
  return [item];
}

const strArray = wrapInArray('hello');
TypeScript infers T as boolean because the array contains booleans.
Typescript
function getFirstElement<T>(arr: T[]): T {
  return arr[0];
}

const first = getFirstElement([true, false]);
Sample Program

This program shows how TypeScript guesses the type T from the input value. It prints the type and value for each call.

Typescript
function echo<T>(input: T): T {
  return input;
}

const numberEcho = echo(123);
const stringEcho = echo('TypeScript');
const booleanEcho = echo(true);

console.log(typeof numberEcho, numberEcho);
console.log(typeof stringEcho, stringEcho);
console.log(typeof booleanEcho, booleanEcho);
OutputSuccess
Important Notes

If TypeScript cannot guess the type, you can specify it manually like echo<string>('hello').

Type inference makes your code cleaner and safer by reducing the need to write types explicitly.

Summary

TypeScript uses the values you pass to guess generic types automatically.

This helps you write flexible and reusable code without extra typing.

You can always specify the type yourself if needed.