Sobes.tech
Middle

Tell me about data types in TypeScript, utility types, the difference between types and interfaces, and inheritance in them.

sobes.tech AI

Answer from AI

TypeScript has several core data types: primitives (string, number, boolean, null, undefined, symbol, bigint), arrays, tuples, enum, any, unknown, void, never, and objects.

Utility types are built-in types that help transform other types. For example:

  • Partial<T> makes all properties of type T optional.
  • Readonly<T> makes all properties of type T read-only.
  • Pick<T, K> selects a subset of properties from T.
  • Omit<T, K> excludes properties from T.
  • Record<K, T> creates an object with keys K and values T.

Difference between types (type) and interfaces (interface):

  • Interfaces are meant to describe object structures and can be extended (inherited) and merged.
  • Types are more versatile, capable of describing not only objects but also unions, intersections, primitives, etc.
  • Interfaces can be declaratively merged (declaration merging), types cannot.

Inheritance:

  • Interfaces are extended using the extends keyword:
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breed: string;
}
  • Types can use intersections to combine:
type Animal = { name: string };
type Dog = Animal & { breed: string };

Thus, interfaces are convenient for describing objects and their extension, while types are more flexible and powerful for complex type combinations.

Tell me about data types in TypeScript, utility… - sobes.tech