Sobes.tech
Middle

Regarding TypeScript — generics, unions, utility types — have you used all of them? Tell me about generics, what did you use them for.

sobes.tech AI

Answer from AI

Generics in TypeScript allow creating components and functions that work with different data types while maintaining type safety. This is especially useful for writing reusable code, such as generic functions or components.

An example of using generics is a function that returns an element from an array by index, with the return type matching the type of the array elements:

function getElement<T>(arr: T[], index: number): T {
  return arr[index];
}

const numbers = [1, 2, 3];
const num = getElement(numbers, 1); // type of num — number

const strings = ['a', 'b', 'c'];
const str = getElement(strings, 0); // type of str — string

Union types allow a variable to accept multiple types, for example string | number. This is useful when a function can work with different input data types.

Utility types are built-in TypeScript types that help transform other types, such as Partial<T>, Readonly<T>, Pick<T, K>, etc. They simplify working with types and make the code more expressive.