interface IName {
name : string;
}
interface ISchool {
school : string;
}
interface ICity {
city : string;
}
function prt(params : any){
if("name" in params) console.log(params.name);
else if("school" in params) console.log(params.school);
else if("city" in params) console.log(params.city);
}
prt({name : "js"})
interface 부분에서
더 늘어나게 된다면 효율성이 떨어짐
interface ISuperKey {
[props: string] : string;
}
function prt(params : ISuperKey){
if("name" in params) console.log(params.name);
else if("school" in params) console.log(params.school);
else if("city" in params) console.log(params.city);
else console.log("error 500");
}
props 안에 key값을 받아 사용
interface IBook {
title : string;
publisher : string;
price : number;
author : string;
}
function prt(params : IBook, key : keyof IBook){
console.log(params[key]);
}
prt(
{
title : "TS 배우기",
publisher : "인프런",
price : 29700,
author : "조용수"
},
"title"
// IBook 타입이 아닌경우 오류
)
키를 한정하여 오류를 잡을 수 있음
interface IUser {
name : string;
age : number;
}
interface IBook {
title : string;
price : number;
}
interface ICart {
userName : string;
bookName : string;
}
interface IUserCartService {
user : IUser;
book : IBook;
cart : ICart;
}
function login(params : IUserCartService["user"]){
console.log(params);
}
login({
name : 'js',
age : 10
})
function searchBook(params : IUserCartService["book"]){
console.log(params);
}
searchBook({
title : "js language",
price : 1000
})
상황에 맞게 사용가능
한 묶음으로 묶어서 관리하기 쉬움