The difference between item[key] vs item.id in TS/JS

This blog is back to basics in TS/JS. The difference between item[key] and item.id. There is a way to access a property of the object

item.id is a Static Property Access:

  • fixed property name that is explicitly defined in the object. - known at compile time
  • Example
const item = { id: 1, name: "Project A" };
console.log(item.id); // Output: 1

item[key] is a Dynamic Property Access:

  • This allows you to dynamically access an object's properties based on the key value. - not known at compile time and is determined dynamically at runtime
  • Example
const key = "name";
const item = { id: 1, name: "Project A" };
console.log(item[key]); // Output: "Project A"

Note: item[key] is more flexible but less type-safe.

Another example

const isInListById = (value: number, list: { id: number }[]) => {
  return list.some(item => item.id === value);
};

const list = [
  { id: 1, name: "Project A" },
  { id: 2, name: "Project B" }
];

console.log(isInListById(1, list)); // Output: true

Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts sent to your email.