ARCHIVE/TypeScript

[TS] instanceof / Class types / Interface

man_on 2022. 1. 1. 04:07
반응형

 

 

 

     


     

     

     

     


    HTML 변경

     

     

    🔻 null이 들어오는 경우 체크해주는 옵션

     

    tsconfig.json 파일에서 "strickNullChecks" 옵션을 true로 지정한다.

    혹은 그냥 "strict" : true 를 하면 strickNullChecks 자동으로 true로 켜진다.

     

     

     

     

    🔻 selector로 html을 찾으면 못찾을 경우가 null값이 되어서 변수가 union type이다. ( Element | null )

    let 제목 = document.querySelector("#title");
    제목.innerHTML = 'hi'    //error

     

     

     

    해결책 1)  narrowing

    if (제목 != null) {
      제목.innerHTML = "hi";
    }

     

     

    해결책2 ) instanceof 사용하는 narrowing

    if (제목 instanceof HTMLElement) {
      제목.innerHTML = "hello";
    }

     

     

    해결책3 ) assertion

    let 제목 = document.querySelector("#title") as HTMLElement;
    제목.innerHTML = "bonjour";

     

     

    해결책4 ) optional chaining

    if (제목?.innerHTML != undefined) {
      제목.innerHTML = "bonsoir";
    }

     

     

     

     

     


     

     

     

     

     

    instanceof 연산자

     

     

    🔻 Object instanceof Class

     : obj가 Class에 속하거나 Class를 상속받는 클래스에 속하면 true가 반환된다.

     

     

     

    🔻html 태그 종류별로 정확한 타입명칭이 있다.

    <a>    HTMLAnchorElement
    <image>    HTMLImageElement
    <h3>     HTMLHeadElement
     

     

    정확한 타입명칭으로 narrowing해야 html속성 수정을 제대로 할 수 있다.

    let 링크 = document.querySelector("#link");
    if (링크 instanceof HTMLAnchorElement) {
      링크.href = "http://kakao.com";
    }

     

     

     


     

     

     

     

    Class types

     

     

    class 타입지정

     : type지정 안해줘도 알아서 타입스크립트가 지정한다.

       굳이 하고싶다면 일반 변수처럼 타입지정해주면 된다.

    class Person {
      data: number = 0;
    }
    
    let kim = new Person();
    let Lee = new Person();
    
    console.log(kim.data);

     

     

     

    constructor 타입지정

     : this를 사용하고싶으면미리 필드값으로 만들어줘야한다.

        필드값이랑 constructor랑 똑같은 역할이지만 new로 생성해서 parameter로 값 전달하고싶으면 constructor로 만들어야한다.

     

    class Person {
      constructor() {
        this.name = "kim";
        this.age = 20;
      }
    }
    // Error : Property 'name' does not exist on type 'Person'
    class Person {
      name;
      age;
      constructor(a: string) {
        this.name = a;
        this.age = 20;
      }
    }
    
    let kim = new Person("kim");

     

     

     

     

    default parameter

    파라미터에 값을 입력안하면 자동으로 할당해주는데, 이런걸 활용하면 타입지정 안해도된다.

    class Person {
      name;
      age;
      constructor(a = 'kim') {
        this.name = a;
        this.age = 20;
      }
    }

     

     

     

    methods 타입지정

    : class 내부에서 함수입력 할 수 있는데, 이 함수는 클래스의 prototype에 추가된다.

    class Person2 {
      add(숫자: number): number {
        console.log(숫자 + 1);
      }
    }
    // Person2의 자식들은 add라는 함수를 이용가능하다.

     

     

     

    ex) constructor과 methods 동시에 type 지정

    class Car {
      model;
      price;
      constructor(a: string, b: number) {
        this.model = a;
        this.price = b;
      }
      tax(): number {
        return this.price * 0.1;
      }
    }

     

     

     

     

     


     

    Interface

     

     

    object 자료형의 타입을 미리 정의해놓고 가져다가 쓴다. (type alias와 용도와 기능이 같다)

    대문자로 작명하고 { } 안에 타입을 명시해 준다.

     

    interface Save {
      color: string;
      width: number;
    }
    
    let 네모: Save = { color: "red", width: 40 };

     

    extends 문법으로 다른 interface 복사해서 확장해 쓸 수 있다.

    interface Save3 extends Save2 {
      height: number;
    }
    
    let 네모2: Save3 = { color: "blue", width: 50, height: 40 };

     

     

     

    🔻type alias와 차이점

       : 거의 같은 기능을 제공하지만, extends 문법이 약간 다르다.

     

     

    Intersection :  type alias는 & 기호로 object 두개를 합칠 수 있다. ( interface도 & 기호로 복사가능 )

     * &로 intersection하면 중복속성 발견될경우 에러 뜨지 않을 수 있다.

    type Animal = {
      name: string;
    };
    
    type Cat = Animal & { legs: number };

     

     

     

    타입이름 중복선언

     

    interface 중복선언 허용 : extends 한 것이랑 동일하게 동작 ( 외부라이브러리 이용시 type 선언 덮어쓰기, override 편리)

    interface Animal { 
      name :string 
    } 
    interface Animal { 
      legs :number 
    }
    
    //Animal이 name과 legs 속성 가짐

     

     

    type alias : 중복선언 허용하지 않음 (에러발생)

    type Animal = { 
      name :string 
    } 
    type Animal = { 
      legs :number 
    }
    // 에러에러

     

     

    > 일반적으로는 type 키워드 사용, 다른사람이랑 같이 코드 활용할 경우 interface로 유연하게 만드는것이 좋다.

       보통 타입스크리트로 작성된 라이브버리들은 interface로 타입 정해 놓은곳이 많다.

     

     

     

    object 속성 중복

     : object내의 속성이 중복되면 interface, type alias 모두 에러발생한다.

    interface Animal { 
      name :string 
    } 
    interface Dog extends Animal { 
      name :number 
    }
    // 에러에러
    interface Animal { 
      name :string 
    } 
    interface Dog { 
      name :number
    } 
    
    let 변수 :Dog & Animal = { name : '멍멍' }
    // 에러에러

     

     

     

    ✔️ class 타입확인 하고 싶을 때 implements

         : implements interfaceName 쓰면 "이 class가 이 interface에 있는 속성 다 들고있는가?" 라고 확인 가능하다.

           빠진 속성있으면 에러발생.

    interface Cartype {
      model: string;
      price: number;
    }
    class Car1 implements Cartype {
      model: string;
      price: number = 1000;
      constructor(a: string) {
        this.model = a;
      }
    }

     

    반응형

    'ARCHIVE > TypeScript' 카테고리의 다른 글

    [TS] declare / d.ts / index signatures  (0) 2022.01.13
    [TS] React  (0) 2022.01.12
    [TS] Private / Static / Generic 등  (0) 2022.01.05
    [TS] Type Aliases / Literal Type  (0) 2021.12.30
    [TS] TypeScript Setting / tsconfig.json  (0) 2021.11.25