interface Axios {
get(): void;
}
class CustomError extends Error {
response?: {
data: any;
};
}
declare const axios: Axios;
(async () => {
try {
await axios.get();
} catch (error: unknown) {
// (1회성).
// 타입스크립트는 건망증이 심함. 앞에 에러를 CustomError로 정의해줬는데 뒤에서 기억못함.
console.error((error as CustomError).response?.data);
error.response?.data; // error.
// ---------
// 위와 같이 매번 as로 단언해주지 않기 위해 아래와 같은 방법으로 사용 가능.
// 변수에 따로 저장해줌.
const customError = error as CustomError;
console.error(customError.response?.data);
customError.response?.data; // 중복 사용 가능
// 실제 프로젝트에서는 위의 코드들처럼 작성하면 안됨.
// if로 타입 검사 먼저
if (error instanceof CustomError) {
console.error(error.response?.data);
error.response?.data;
}
}
})();
interface Axios {
get(): void;
}
class CustomError extends Error {
response?: {
data: any;
};
}
declare const axios: Axios;
(async () => {
try {
await axios.get();
} catch (error: unknown) {
const customError = error as CustomError;
console.error(customError.response?.data);
customError.response?.data; // 중복 사용 가능
// 실제 프로젝트에서는 위의 코드들처럼 작성하면 안됨.
// if로 타입 검사 먼저
if (error instanceof CustomError) {
console.error(error.response?.data);
error.response?.data;
}
}
})();
※ 즉, 다른 라이브러리에서 타입 unknown을 하면, as로 타입 캐스팅을 해야하는데, 타입 가드로 좁혀놨으면 그 안에서 as 안써도 된다.
interface Profile {
name: string;
age: number;
married: boolean;
}
// 기본
const human1: Profile = {
name: "nini",
age: 27,
married: false,
};
// 인터페이스 속성 중 일부를 안넣고 싶을 때
// 1) Partial
// <>에 나오는 타입의 속성을 모두 옵셔널로 만들어줌.
const human2: Partial<Profile> = {
name: "lili",
age: 26,
};
// 1. Pick
// Pick에 넣어준 Profile 타입에서 필요한 몇 개를 가져온다.
// type P<T, S extends keyof T> = {
// [Key in keyof S]: T[Key];
// };
const human2: Pick<Profile, "name" | "age"> = {
name: "lili",
age: 26,
};
// 2. Omit
// 타입의 속성이 많을 때, 빼고 싶은 속성을 나타냄.
const human2: Omit<Profile, "married"> = {
name: "lili",
age: 26,
};
※ 제네릭을 사용할 때 제한조건을 먼저 걸어주자.
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;