[TS] 클래스와 대수타입

단비·2023년 3월 6일
0

인강

목록 보기
4/15
  • 클래스
    • public

      • 접근(get), 설정(set) 2개가 외부, 내부 자유로움
    • protected

      • 접근(get), 설정(set) 2개가 자기 자신한테만 허용 + 자신을 상속한 자식한테도 허용
    • private
      - 접근(get), 설정(set) 2개가 자기 자신한테만 허용
      - 해당 변수의 앞에 _ 를 붙이는 것이 관례

      class UserInfo {
          private _age: number;
          private _phone: string;
      
          constructor(age: number, phone: string){
              this._age = age;
              this._phone = phone;
          }
      
          get phone(): string {
              return (
                  this._phone.slice(0, 3) + "-" + 
                  this._phone.slice(3, 7) + "-" +
                  this._phone.slice(7, 12)
              )
          }
          set phone(newPhone: string){
              this._phone = newPhone
          }
      
          get age(){
              return this._age
          }
          set age(newAge: number){
              if(newAge <= 0) this._age = 0;
              else this._age = newAge;
          }
      }
      
      const user = new UserInfo(-25, "01012345678") // 0, 010-1234-5678

  • readonly 속성
    • 초기 세팅만 가능하고 이후 값 변경이 불가능함
  • 클래스의 생성자
    • 생성자 매개변수에 기본값을 설정할 수 있음

    • 필드명에 ?를 붙여 null이여도 오류가 발생하지 않음

      class LoginDataTransferObject {
          public readonly ID;
          private readonly _PW?;
      
          constructor(ID: string, PW: string = "defualt password"){
              this.ID = ID;
              this._PW = PW;
          }
      }
      const LoginDTO = new LoginDataTransferObject("hi");
      // LoginDataTransferObject { ID: 'hi', _PW: 'defualt password' }
    • 생성자를 이용한 클래스 선언 축약형
      - 필드명과 생성자의 매개변수와 이름이 동일하게 세팅됨

      class LoginDataTransferObject2 {
          constructor(public readonly ID: string, public PW?: string){}
      }
      const LoginDTO2 = new LoginDataTransferObject2("hi");

🌈 클래스를 이용해 인스턴스를 만들 수 있지만 타입으로도 사용 가능

  • 인스턴스란, 클래스를 통해서 구현해야할 대상(객체)이 실제로 구현된 구체적인 실체
const testDto: testClass = new testClass("test");

  • 합집합(union, | , OR)
    1. 변수 자체에 선언

      let nameOrAge: string | number
      nameOrAge = "danbi";
      nameOrAge = 25;
    2. 인터페이스 활용

      interface IName {
          name: string;
      }
      interface IAge {
          age: number;
      }
      type MyType = IName | IAge;
      
      // function prtUnion(params: IName | IAge){
      function prtUnion(params: MyType){
          // name 정보가 들어왔을 때 로직
          if("name" in params){
              console.log(params.name)
          }
          // age 정보가 들어왔을 때 로직
          if("age" in params){
              console.log(params.age)
          }
      }
  • 교집합(intersection, & , AND)
    • 두 조건 모두 충족

      interface IIName {
          name: string;
      }
      interface IIAge {
          age: number;
      }
      const nameAndAge: IName & IAge = {
          name: "danbi",
          age: 25
      }
profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글