Refactor extractFromEntry to TypeScript

Here is the current extractFromEntry function:

const extractFromEntry = (data, key) => {
  if (data && Array.isArray(data)) {
    return data[0][key];
  }
};

This function takes the API response array and a property key, and returns that property from the first entry. It works, but TypeScript does not know what types data, key, or the return value are. Let’s fix that.

Adding Type Annotations with Generics

Here is the refactored version:

const extractFromEntry = <K extends keyof DictionaryAPIResponse>(
  data: DictionaryAPIResponse[] | undefined,
  key: K,
): DictionaryAPIResponse[K] | undefined => {
  return data?.[0]?.[key] ?? undefined;
};

Let’s break down the changes:

  • <K extends keyof DictionaryAPIResponse> is a generic type parameter. It tells TypeScript that K must be one of the valid property names of DictionaryAPIResponse (like "meanings", "phonetics", "word", etc.).

  • key: K constrains the key argument so TypeScript will error if you pass an invalid key like extractFromEntry(data, "foo").

  • DictionaryAPIResponse[K] is a lookup type. The return type is automatically inferred from the key, so the compiler knows exactly what type each call returns.

  • We use optional chaining (?.) and the nullish coalescing operator (??) to safely access nested properties and handle cases where a value is null or undefined.

Usage:

const meanings = extractFromEntry(data, "meanings"); // Meaning[] | undefined
const phonetics = extractFromEntry(data, "phonetics"); // Phonetic[] | undefined

Optional Chaining (?.)

The optional chaining operator (?.) lets you read a nested property without an error when something along the way is null or undefined. If the value you are reading from is null or undefined, the expression stops right there and returns undefined. That is how you avoid a TypeError when you reach into nested data.

Nullish Coalescing Operator (??)

The nullish coalescing operator (??) gives you a default value when a value is null or undefined. If the value on the left side of the operator is null or undefined, the operator returns the value on the right side. Otherwise, it returns the value on the left side. Use it when you need a fallback for a value that might be null or undefined.

The ?? is a shorter way of writing the following conditional expression:

const value =
  someValue !== null && someValue !== undefined ? someValue : defaultValue;

Together, optional chaining and the nullish coalescing operator let us write the original if guard and array access as a single line.

Checkpoint: Commit your progress.

git add .
git commit -m "dictionary-05: Refactor extractFromEntry with TypeScript generics"
git push