
catch의 변수 타입을 string으로 지정하면 아래와 같은 에러가 발생한다.
에러 타입에 string 대신 any 또는 unknown을 사용해야 하지만, any는 가능한 피하고 싶어서 다른 방법을 찾아보았다.
const fetchData = async () => {
try {
const [latestVersion, rotationResponse, championsData] = await Promise.all([
fetchLatestVersion(),
fetch("/api/rotation"),
fetchChampionList(),
]);
const rotationData = await rotationResponse.json();
setVersion(latestVersion);
setChampionRotation(rotationData);
setChampions(championsData);
} catch (error: string) { // 🚨 Catch clause variable type annotation must be 'any' or 'unknown' if specified.
setError(`Error: ${error.message}`);
} finally {
setLoading(false);
}
};
try...catch 문을 사용할 때, catch에서 넘어오는 error는 어떤 타입이든 올 수 있다. 그래서 타입을 지정하려면 any나 unknown을 사용해야 한다.
throw "What the!?"; // string
throw 7; // number
throw { wut: "is this" }; // object
throw null; // null
throw new Promise(() => {}); // Promise
throw undefined; // undefined
타입 가드를 활용하여 error가 Error타입인지 체크한 후에 적절한 처리를 해준다.
타입 가드란?
특정 조건을 통해 변수의 타입을 좁히는 기법
const fetchData = async () => {
try {
const [latestVersion, rotationResponse, championsData] = await Promise.all([
fetchLatestVersion(),
fetch("/api/rotation"),
fetchChampionList(),
]);
const rotationData = await rotationResponse.json();
setVersion(latestVersion);
setChampionRotation(rotationData);
setChampions(championsData);
} catch (error) {
// ✅ 타입가드
let message;
if (error instanceof Error) message = error.message; // ✅ Error 타입일 경우 메시지 사용
else message = String(error); // ✅ 아닐 경우, 오류를 문자열로 변환
setError(message);
} finally {
setLoading(false);
}
};