Difference Between Record vs Object in TypeScript

TypeScript is a powerful language that builds on JavaScript by adding static type definitions. This feature helps developers catch errors early and ensures that their code is more predictable and maintainable.

Among the many types available in TypeScript, understanding the difference between Record and Object is essential for every TypeScript developer.

This tutorial will learn about the differences between record vs object in TypeScript, their use cases, and provide detailed examples to help you understand when to use each.

What is an object in TypeScript?

In TypeScript, the object type is a broad type that represents any non-primitive type, which includes arrays, functions, objects, and more. Essentially, it is a type that is not number, string, boolean, symbol, null, or undefined.

Example of object Type

let obj: object;
obj = { name: "John", age: 30 }; // valid
obj = [1, 2, 3]; // valid
obj = function () {}; // valid
obj = null; // invalid
obj = 42; // invalid

In the example above, obj it can be assigned any value that is not a primitive type. This makes object a versatile but somewhat loosely defined type.

What is a Record in TypeScript?

The Record utility type in TypeScript allows you to define an object type with specific keys and a uniform value type. It is a generic type with two parameters: K (the type of keys) and T (the type of values).

Syntax of Record:

Record<K extends keyof any, T>
  • K: The type of the keys, which can be string, number, or symbol.
  • T: The type of the values.

Example of Record Type:

type User = Record<string, number>;

const userAges: User = {
  Alice: 25,
  Bob: 30,
  Charlie: 35,
};

In this example, User is a type where the keys are strings and the values are numbers. This provides a clear and consistent structure for the userAges object.

Difference Between Record vs Object in TypeScript

  1. Flexibility vs. Specificity:
  • object is more flexible and can represent any non-primitive type.
  • Record is more specific, defining an object with a particular key and value type.
  1. Type Safety:
  • object offers less type safety since it can be any non-primitive type.
  • Record offers more type safety by enforcing consistent key and value types.
  1. Use Cases:
  • Use object when you need a generic type that can represent any non-primitive value.
  • Use Record when you need a well-defined object structure with specific key and value types.

Detailed Examples of Record and Object in TypeScript

Below I have explained the detailed examples of record and object in TypeScript.

Using object Type:

function logObject(obj: object): void {
  console.log(obj);
}

logObject({ name: "Alice", age: 25 });
logObject([1, 2, 3]);
logObject(() => console.log("Hello"));

In this function, logObject it accepts any non-primitive type. This demonstrates the flexibility of the object type.

Object Type Example Using TypeScript

Using Record Type:

type Product = Record<string, number>;

const productPrices: Product = {
  apple: 1.2,
  banana: 0.8,
  cherry: 2.5,
};

function logProductPrices(products: Product): void {
  for (const [product, price] of Object.entries(products)) {
    console.log(`${product}: $${price}`);
  }
}

logProductPrices(productPrices);

In this example, Product is a type where the keys are strings (product names) and the values are numbers (prices). The logProductPrices function then logs each product and its price, demonstrating the type safety and structure provided by Record.

Difference Between Record vs Object in TypeScript

Summary in Tabular Format

FeatureobjectRecord<K, T>
FlexibilityHighModerate
Type SafetyLowHigh
Key TypeAny non-primitive typeSpecific type (string, number, symbol)
Value TypeAny non-primitive typeSpecific type
Use CaseGeneric non-primitive valuesWell-defined object structures

Conclusion

Both object and Record types in TypeScript serve important roles and understanding their differences is crucial for effective type management. The object type is versatile and can represent any non-primitive value, making it useful for generic programming.

On the other hand, the Record type provides a structured and type-safe way to define objects with specific key and value types, making it ideal for scenarios where a consistent object structure is required.

When deciding which type to use, consider the level of type safety and specificity your application needs. For flexible and generic use cases, object is appropriate. For scenarios requiring a well-defined and consistent object structure, Record is the better choice.

By understanding and utilizing these types effectively, you can write more predictable, maintainable, and type-safe TypeScript code.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.