[TS] key를 활용한 제네릭과 타입

단비·2023년 3월 7일
0

인강

목록 보기
5/15
  • 인터페이스에서 []를 이용한 key의 type 세팅
    • props(key name)은 자유롭게 선언 가능하며, 아래의 경우 string 타입만 해당됨

      interface ISuperKey {
          [props: string]: string;
      }
      
      function prt2(params: ISuperKey){
          if("name" in params) console.log(params.name)
          else console.log("error 500")
      }
      prt2({ name: "danbi" }) // danbi
      prt2({ nam2e: "danbi" }) // error 500
  • keyof
    • 객체의 속성들을 유니온(OR) 타입으로 만들어주는 연산자

      function prt(params: IBook, key: keyof IBook){
          console.log(params[key]); // 베르나르 베르베르
      }
      
      prt(
          {
              title: "파피용",
              publisher: "출판사",
              price: 29700,
              author: "베르나르 베르베르"
          },
          "author"
      )

      🍋 typeof : 객체 데이터를 객체 타입으로 변환해주는 연산자(클래스의 경우 타입 자체가 객체 타입이 될 수 있기 때문에 선언 불가능, 인터페이스는 자체가 타입이기 때문에 불가능)


  • 여러 인터페이스를 활용한 타입 설정
    1. 필요한 데이터 별로 인터페이스를 생성

    2. 통합 인터페이스를 생성 후 key(타이틀)에 해당 인터페이스를 타입으로 설정

    3. 사용 시 해당 key 값을 꺼내 타입으로 설정

      interface IUser {
          name: string;
          age: number;
      }
      
      interface IBook1{
          title: string;
          price: number;
      }
      
      interface IUserCartService {
          user: IUser;
          book: IBook1;
      }
      
      function login(params: IUserCartService['user']){
      		...
      }
      login({
          name: 'danbi', age: 25
      })

  • 제네릭
    • T(Type), E(Element), K(Key), V(Value)

      interface IGene<T, U> {
      		// T 타입의 배열
          data: Array<T>;
      		// U 타입
          name: U;
      }
      
      function prt4(params: IGene<number, string>){
      		// object
          console.log(typeof params.data)
      }
      prt4({ data: [1,2,3], name: "danbi" })
    • extends

      • 상속된 타입만 설정 가능
      1. 제한 안전성

        function prt5<T extends string | number, U extends boolean | object>(params: T, params2: U){
            if(typeof params === 'string') console.log("문자열 입니다")
            else if(typeof params === 'number') console.log('숫자입니다')
        
            if(typeof params2 === 'boolean') console.log("불리언 입니다")
            else if(typeof params2 === 'object') console.log('객체입니다')
        }
        prt5<string, boolean>("하하하", true)
        prt5<number, object>(25, {})
      2. 보장
        1. 인터페이스 없이 함수 호출 시 params의 hi라는 함수가 있는지 보장되지 않기 때문에 오류 발생
        2. 인터페이스를 생성하여 hi의 네임 매개변수를 string으로 설정해준 뒤 리턴X

        interface IHi {
            hi: (name: string) => void
        }
        function execute<T extends IHi>(params: T){
            params.hi("danbi")
        }
        execute({ 
            hi(name: string) {
                console.log("hi!", name)
            } 
        })
  • keyof와 제네릭의 혼합사용
    interface IOb1 {
        name: string;
        age: number
    }
    interface IOb2 {
        city: string;
        phone: string
    }
    
    function prtKey<T extends object, U extends keyof T>(params: T, key: U): T[U]{
        console.log(params[key]);
        return params[key]
    }
    prtKey<IOb1, keyof IOb1>({ name: 'danbi', age: 25 }, "name")
    prtKey<IOb2, keyof IOb2>({ city: 'danbi', phone: "01012345678" }, "phone")
profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글