BEST SITE FOR WEB DEVELOPERS
TypeScript. Lessons for beginners

Ua Es De

TypeScript Basic Generics


Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use.

Generics make it easier to write reusable code.


Functions

Generics with functions help make more generalized methods which more accurately represent the types used and returned.

Example

function createPair<S, T>(v1: S, v2: T): [S, T] {
  return [v1, v2];
}
console.log(createPair<string, number>('hello', 42)); // ['hello', 42]
Try it Yourself »

TypeScript can also infer the type of the generic parameter from the function parameters.


Classes

Generics can be used to create generalized classes, like Map.

Example

class NamedValue<T> {
  private _value: T | undefined;

  constructor(private name: string) {}

  public setValue(value: T) {
    this._value = value;
  }

  public getValue(): T | undefined {
    return this._value;
  }

  public toString(): string {
    return `${this.name}: ${this._value}`;
  }
}

let value = new NamedValue<number>('myNumber');
value.setValue(10);
console.log(value.toString()); // myNumber: 10
Try it Yourself »

TypeScript can also infer the type of the generic parameter if it's used in a constructor parameter.


Type Aliases

Generics in type aliases allow creating types that are more reusable.

Example

type Wrapped<T> = { value: T };

const wrappedValue: Wrapped<number> = { value: 10 };

This also works with interfaces with the following syntax: interface Wrapped<T> {


Default Value

Generics can be assigned default values which apply if no other value is specified or inferred.

Example

class NamedValue<T = string> {
  private _value: T | undefined;

  constructor(private name: string) {}

  public setValue(value: T) {
    this._value = value;
  }

  public getValue(): T | undefined {
    return this._value;
  }

  public toString(): string {
    return `${this.name}: ${this._value}`;
  }
}

let value = new NamedValue('myNumber');
value.setValue('myValue');
console.log(value.toString()); // myNumber: myValue

Extends

Constraints can be added to generics to limit what's allowed. The constraints make it possible to rely on a more specific type when using the generic type.

Example

function createLoggedPair<S extends string | number, T extends string | number>(v1: S, v2: T): [S, T] {
  console.log(`creating pair: v1='${v1}', v2='${v2}'`);
  return [v1, v2];
}

This can be combined with a default value.


TypeScript Exercises

Test Yourself With Exercises

Exercise:

Complete the Generic:

function createPair, (x: typeX, y: typeY): [typeX, typeY] {
 return [x, y];
}
console.log(createPair<string, number>('Meaning', 42));


What are generics in plain language?

Think of generics as universal containers that can be used to store any type of data.

For example, imagine you have a box for storing apples. This box can only contain apples. But what if you need a box that can hold not only apples but also other fruits like bananas or oranges? This is where generics come in.

Generics in TypeScript allow you to create types that can work with data of any type.

For example, you can create a function that can sort any array, whether it contains numbers, strings, or other data types.

Here is an example of a generic:

function sort<T>(array: T[]): T[] {
  // ... код сортування ...
  return array;
}

In this example, sort is a generic function that accepts an array array of any type T and returns a sorted array of the same type.

Here are some more examples of generics:

  • Array<T> - type that represents an array of data of type T.
  • Map<K, V> - a type that represents a dictionary where keys are of type K and values are of type V.
  • Promise<T> - type that represents a promise that will be resolved by a value of type T.

Conclusion

Generics make TypeScript code more flexible and reusable. Thanks to generics, you don't need to write separate code to work with different data types.

If you're new to TypeScript, don’t worry if generics seem difficult. With time and practice, you'll get a better understanding of how they work and be able to use them in your code.

You can read more about generics on the official TypeScript website at the link: https://www.typescriptlang.org/docs/handbook/2/generics.html



Comments