# TypeScript Generics Explained Simply: T, extends and Default Types

## What are generics in TypeScript?

Generics let you write one function, type or class that works with many types, without losing information about which type it is. You can think of a generic as a **variable for a type**: the code says "I will work with some type `T`", and the type is filled in when you use it.

If you know normal functions, the idea is the same. A function parameter is a placeholder for a value, and a type parameter is a placeholder for a type.

In this post I will start with a very small example, `first<T>(items: T[])`, and then add constraints (`extends`) and default types.

## The problem generics solve

Let's write a function that returns the first element of an array. The first idea is to use `any`:

```ts
function firstAny(items: any[]): any {
    return items[0];
}

const nickname = firstAny(['Neo', 'Trinity']);
// nickname is any, TypeScript forgot that it is a string

nickname.toFixed();
// No error at compile time, crash at runtime
```

The function works, but the type information is lost. Another idea is to write one function for each type:

```ts
function firstString(items: string[]): string | undefined {
    return items[0];
}

function firstNumber(items: number[]): number | undefined {
    return items[0];
}
// ...and again for Player, boolean, and so on
```

This is safe, but it is the same code repeated again and again. We want the function to say: "whatever type the array has, I return that same type". That is exactly what generics do.

## Your first generic function

Here is the generic version:

```ts
function first<T>(items: T[]): T | undefined {
    return items[0];
}
```

The part `<T>` after the function name declares a **type parameter**. Inside the function you can use `T` like any other type. Here it says: "`items` is an array of some type `T`, and the result is a `T` (or `undefined` if the array is empty)".

Now TypeScript decides what `T` is when you call the function:

```ts
const nickname = first(['Neo', 'Trinity']);
// T is string, so nickname is string | undefined

const level = first([10, 20, 30]);
// T is number, so level is number | undefined

const player = first([{ nickname: 'Neo', level: 1 }]);
// T is { nickname: string; level: number }

nickname?.toUpperCase(); // OK
level?.toUpperCase();
// Error: Property 'toUpperCase' does not exist on type 'number'
```

This is called **type inference**. TypeScript looks at the argument, sees `string[]`, and fills in `T = string` for you. You almost never have to write it yourself.

If you want, you can set the type explicitly:

```ts
const nickname = first<string>(['Neo', 'Trinity']);

first<string>([1, 2, 3]);
// Error: Type 'number' is not assignable to type 'string'
```

The name `T` is only a convention (from "Type"). You can use any name, and for more than one parameter people often use `K` and `V` (key and value) or longer names like `TItem`.

The type parameter can be used in arrow functions too:

```ts
const last = <T>(items: T[]): T | undefined => items[items.length - 1];
```

## Constraints with extends

Sometimes `T` cannot be literally anything. Look at this function:

```ts
function longest<T>(a: T, b: T): T {
    return a.length >= b.length ? a : b;
    // Error: Property 'length' does not exist on type 'T'
}
```

TypeScript is right: `T` could be a number, and numbers have no `length`. We need to tell it that `T` must have a `length`. This is done with `extends`, which creates a **constraint**:

```ts
function longest<T extends { length: number }>(a: T, b: T): T {
    return a.length >= b.length ? a : b;
}

console.log(longest('Neo', 'Trinity'));
// Output: Trinity

console.log(longest([1, 2], [1, 2, 3]));
// Output: [1, 2, 3]

longest(10, 20);
// Error: Argument of type 'number' is not assignable
// to parameter of type '{ length: number; }'
```

Read `T extends { length: number }` as "`T` can be any type, as long as it has a numeric `length`". Strings and arrays both fit. Numbers do not.

In generics, `extends` does not mean class inheritance. It means "is assignable to" or "has at least this shape".

### Constraint with keyof

A very useful pattern is a function that reads a property by name. The second type parameter depends on the first one:

```ts
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];
}

const player = { nickname: 'Neo', level: 1 };

const nickname = getProperty(player, 'nickname'); // string
const level = getProperty(player, 'level');       // number

getProperty(player, 'age');
// Error: Argument of type '"age"' is not assignable
// to parameter of type '"nickname" | "level"'
```

Here `keyof T` is a union of all property names of `T`, and `K extends keyof T` means "`K` must be one of those names". The return type `T[K]` is the type of that exact property, so TypeScript knows that `nickname` is a string and `level` is a number. With `any` you could not get this.

## Default types

Just like function parameters can have default values, type parameters can have **default types**. TypeScript uses the default when it cannot infer the type and you do not provide one.

```ts
interface ApiResponse<T = unknown> {
    data: T;
    error?: string;
}

const raw: ApiResponse = { data: 'anything' };
// T is unknown, because we did not write <...>

const response: ApiResponse<{ nickname: string }> = {
    data: { nickname: 'Neo' },
};
// T is { nickname: string }

console.log(response.data.nickname);
// Output: Neo
```

Without the default, `const raw: ApiResponse` would be an error: `Generic type 'ApiResponse' requires 1 type argument(s)`. With `= unknown`, the type can be used both with and without an argument.

I chose `unknown` as the default, not `any`, so a user who forgets to give the type still has to check the value before using it (more about this in my post about `any`, `unknown` and `never`).

Defaults work together with constraints. The constraint goes first, then the default:

```ts
interface Repository<T extends { id: number } = { id: number }> {
    getById(id: number): T | undefined;
    save(item: T): void;
}
```

This reads: "`T` must have an `id` number, and if you do not say anything, it is just `{ id: number }`". One more rule: parameters with defaults must come after the ones without defaults, like in normal functions.

## Generic types, interfaces and classes

Generics are not only for functions. You can use them in type aliases, interfaces and classes. A classic example is a stack, where you can put any type of item, but every item in one stack has the same type.

```ts
class Stack<T> {
    #items: T[] = [];

    push(item: T): void {
        this.#items.push(item);
    }

    pop(): T | undefined {
        return this.#items.pop();
    }

    get size(): number {
        return this.#items.length;
    }
}

const names = new Stack<string>();
names.push('Neo');
names.push('Trinity');

console.log(names.pop());
// Output: Trinity

names.push(42);
// Error: Argument of type 'number' is not assignable to parameter of type 'string'
```

The type is chosen when you create the object: `new Stack<string>()`. After that, every method knows that it works with strings. Notice the `#items` field here, the private fields from my post about encapsulation work nicely with generic classes.

A generic type alias works in a similar way. Here is a small helper that describes a result that either succeeds or fails:

```ts
type Result<T, E = string> =
    { success: true; value: T }
    | { success: false; error: E };

const ok: Result<number> = { success: true, value: 42 };
const fail: Result<number> = { success: false, error: 'Not found' };
```

This one has **two** type parameters, and the second one (`E`) has a default, so most of the time you only write `Result<number>`.

You already use generics every day, maybe without noticing: `Array<string>` (the same as `string[]`), `Promise<number>`, `Map<string, number>` and the utility type `Partial<Player>` are all generic types.

## Common mistakes

### 1\. A type parameter that is used only once

A generic is useful when it **connects** things, for example the type of the argument and the type of the result. If `T` appears only once, it does nothing.

```ts
function log<T>(value: T): void {
    console.log(value);
}
// T connects nothing, so this is the same as:

function log(value: unknown): void {
    console.log(value);
}
```

A good question to ask yourself: "does `T` appear at least twice in the signature?" If not, you probably do not need it.

### 2\. Using any inside a generic function

A generic does not save you if you cast the value to `any` inside it, because you are turning off the checks again:

```ts
function first<T>(items: T[]): T {
    return (items as any)[0] as T; // no help from TypeScript here
}
```

### 3\. Forgetting the constraint, and using too many

If you need a property or a method of `T`, add `extends` as a constraint instead of casting. On the other hand, do not make the constraint stricter than the function needs, because a simple constraint like `{ length: number }` is more flexible than a whole `Player` type.

### 4\. Generic arrow functions in .tsx files

In a React file (`.tsx`), `<T>` looks like a JSX tag, so this does not work:

```tsx
const identity = <T>(value: T) => value; // error in .tsx
```

Add a comma or a constraint to fix it:

```tsx
const identity = <T,>(value: T) => value;
const identity2 = <T extends unknown>(value: T) => value;
```

## Summary

Generics are type variables. They let one function, interface or class work with many types and still remember which type it is, as in `first<T>(items: T[])`. Use `extends` when `T` must have a certain shape, use `keyof` to connect a key with its value type, and use defaults (`<T = unknown>`) to make the type argument optional. Remember that most of the time TypeScript infers `T` for you, and that a type parameter should connect at least two places in your code.
