타입스크립트 타입 별칭 예제
-
타입스크립트에는 type 키워드가 있다.
type 키워드는 타입을 별칭( Alias )를 설정하여 사용하는 것으로,
반복해서 쓰는 타입에 이름을 붙여 재사용할 수 있도록 하고 있다.
type 키워드를 사용하는 대표적은 것이 객체 타입 또는 유니온 타입, 함수, 제너링 등이이다.
이들의 특징은 여러 곳에서 반복해서 사용할 수 있다는 점에 있다.
즉, type 키워드는
반복해서 사용할 수 있는 타입에 별칭을 붙여 사용할 수 있도록 한다.
-
type UserName = string;
const name: UserName = "Kim";-
const name1: string = "Kim";
type UserName = string;
const name2: UserName = "Lee";-
type 별칭이름 = 타입;-
type Age = number;
type IsActive = boolean;
type UserId = string;-
type UserId = string;
function getUser(id: UserId) {
console.log(id);
}
getUser("user-001");-
type User = {
id: number;
name: string;
email: string;
};
const user: User = {
id: 1,
name: "Kim",
email: "kim@example.com",
};-
function printUser(user: { id: number; name: string; email: string }) {
console.log(user.name);
}-
type User = {
id: number;
name: string;
email: string;
};
function printUser(user: User) {
console.log(user.name);
}-
type Product = {
id: number;
name: string;
price: number;
description?: string;
};
const product: Product = {
id: 1,
name: "Keyboard",
price: 50000,
};-
type Status = "pending" | "success" | "error";
let status: Status = "pending";
status = "success";
status = "error";
// 오류 예시
// status = "done";-
type ApiStatus = "idle" | "loading" | "success" | "error";
function showMessage(status: ApiStatus) {
if (status === "loading") {
return "불러오는 중입니다.";
}
if (status === "success") {
return "요청에 성공했습니다.";
}
if (status === "error") {
return "오류가 발생했습니다.";
}
return "대기 중입니다.";
}-
type Add = (a: number, b: number) => number;
const add: Add = (a, b) => {
return a + b;
};-
type ClickHandler = (eventName: string) => void;
function buttonClick(handler: ClickHandler) {
handler("submit");
}
buttonClick((eventName) => {
console.log(`${eventName} 버튼 클릭`);
});-
function buttonClick(handler: (eventName: string) => void) {
handler("submit");
}-
type ClickHandler = (eventName: string) => void;-
type UserNameList = string[];
const users: UserNameList = ["Kim", "Lee", "Park"];-
type User = {
id: number;
name: string;
};
type UserList = User[];
const userList: UserList = [
{ id: 1, name: "Kim" },
{ id: 2, name: "Lee" },
];-
type ApiResponse<T> = {
data: T;
message: string;
success: boolean;
};-
type User = {
id: number;
name: string;
};
type UserResponse = ApiResponse<User>;
const response: UserResponse = {
data: {
id: 1,
name: "Kim",
},
message: "사용자 조회 성공",
success: true,
};-
type UserListResponse = ApiResponse<User[]>;
const response: UserListResponse = {
data: [
{ id: 1, name: "Kim" },
{ id: 2, name: "Lee" },
],
message: "사용자 목록 조회 성공",
success: true,
};-
-
-
-
-
-
-
-
-
댓글
댓글 쓰기