| key와 같이 쓰는 타입
타입이 고정되어있을때
interface IName {
name: string;
}
interface ISchool {
school: string;
}
interface ICity {
city: string;
}
function prt(params: IName | ISchool | ICity){
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: "jae"});
만약 인터페이스가 더 늘리려고 하면 인터페이스를 하나하나 작성해야해서 번거로울 것이다.
위의 코드를 보면 인터페이스들의 타입들이 string으로 고정되어있는것을 알 수 있다
이럴땐 아래와 같이 [ ] 를 사용하여 더 효율적으로 작성이 가능하다
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")
}
prt({name: "jae"});
만약 분기에 해당하지 않는 키값을 넣었을경우
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")
}
prt({nameaaaa: "jae"});
keyof
만약 객체를 받고 받은 객체에서 특정 키의 값을 뽑고싶을때는 아래와같이 적으면된다
interface IBook{
title: string;
publisher: string;
price: number;
author: string;
}
function prt(params: any, key: string){
console.log(params[key]);
}
prt(
{
title: "ts 배우기",
publisher: "인프런",
price: 29700,
author: "jae",
},
"titlee"
);
특정 객체의 타입을 IBook 으로 제한하고싶으면 any 대신 IBook 를 적으면된다
interface IBook{
title: string;
publisher: string;
price: number;
author: string;
}
function prt(params: IBook, key: string){
console.log(params[key]);
}
prt(
{
title: "ts 배우기",
publisher: "인프런",
price: 29700,
author: "jae",
},
"titlee"
);
그럼 아래와같이 에러가 난다
이유는 받을 객체의 타입은 IBook으로 정했는데
key 의 타입은 string이므로 IBook에 없는 키값이 들어올수 있기때문이다
그래서 이럴때는 키값을 IBook에 있는 값들로만 한정해줘야한다
그럴때 사용하는것이 바로 keyof이다
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: "jae",
},
"titlee"
);
keyof를 써주면 titlee에 없는 키값이라고 빨간줄이 뜬다
관련있는 인터페이스를 묶어서 사용하기
만약 장바구니 기능을 구현하려고한다
interface IUser{
name: string;
age: number;
}
interface IBook2{
title: string;
price: number;
}
interface ICart{
userName: string;
bookName: string;
}
이 세 인터페이스는 장바구니 라는 공통점이 있다
그래서 셋의 소속을 만들어주는 것이다
interface IUser{
name: string;
age: number;
}
interface IBook2{
title: string;
price: number;
}
interface ICart{
userName: string;
bookName: string;
}
interface IUserCartService {
user: IUser;
book: IBook2;
cart: ICart;
}
function login(params: IUserCartService["user"]){
// 유저가 로그인하는 로직
console.log(params);
}
login({name: "jae", age: 25})
function searchBook2(params: IUserCartService["book"]){
// 책을 검색하는 로직
console.log(params);
}
searchBook2({title: "jae", price: 25})
function addBookToMyCart(params: IUserCartService["cart"]){
// 책을 검색하는 로직
console.log(params);
}
addBookToMyCart({userName: "jae",bookName: "jae TS"})
[ ] 를 사용해서 장바구니인터페이스에서 원하는 타입의 객체 파라미터를 받을 수 있다.
반응형
'웹 개발 > #️⃣ TypeScript' 카테고리의 다른 글
TS | 데코레이터 (0) | 2023.06.05 |
---|---|
TS | 제네릭 (0) | 2023.06.04 |
TS | 대수타입 -union, intersection (0) | 2023.06.01 |
TS | 클래스 - readonly와 생성자 (0) | 2023.06.01 |
TS | 클래스 - 접근제한자와 getter setter (0) | 2023.06.01 |