Refactor searchWord to TypeScript
Here is the searchWord function:
// Fetch data from the API
const searchWord = async (word) => {
const response = await fetch(`${dictionaryAPI}${word}`);
if (!response.ok) {
throw new Error(`Word not found (status ${response.status})`);
}
return response.json();
};
We can refactor this function to include type annotations for the word parameter and the return value.
// Fetch data from the API
const searchWord = async (word: string): Promise<DictionaryAPIResponse[]> => {
const response = await fetch(`${dictionaryAPI}${word}`);
if (!response.ok) {
throw new Error(`Word not found (status ${response.status})`);
}
const data: DictionaryAPIResponse[] = await response.json();
return data;
};
Let’s break down the changes:
- We added a type annotation for the
wordparameter:word: string. This specifies that thewordparameter should be a string. - We added a type annotation for the
datavariable:const data: DictionaryAPIResponse[]. This specifies that thedatavariable should be an array ofDictionaryAPIResponseobjects. - We added a return type annotation for the function:
Promise<DictionaryAPIResponse[]>. This specifies that the function returns a promise that resolves to an array ofDictionaryAPIResponseobjects.
Let’s look at the syntax of the return type annotation: Promise<DictionaryAPIResponse[]>. This says the searchWord function returns a promise. The angle brackets (< >) contain the type of the resolved value of the promise. If you have worked with generics in other languages, like Java, this syntax might look familiar.
You might be wondering why we use Promise<DictionaryAPIResponse[]> instead of just DictionaryAPIResponse[]. The reason is that the searchWord function is asynchronous. It does not return the array directly; it returns a promise that resolves to the array. So we wrap the type in Promise. If the API call fails (for example, the word is not found), the function throws an error, which rejects the promise instead of resolving to a value. So the return type only has to describe the success case.
Checkpoint: Commit your progress.
git add .
git commit -m "dictionary-04: Refactor searchWord function with type annotations"
git push