ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 7. Interface
    Typescript 2022. 10. 19. 15:31

     

     

    Interfaces
    • 오직 객체 생성에만 사용
    • 생성한 인터페이스가 객체가 되기위해 필요한 속성 모음
    • Custom Type 과 거의 동일하게 동작
    • interface Keyword { ... }
    interface Person {
    	readonly id: number
            first: string
            last: string
            nickname?: string
    }
    
    let tomas: Person = {
    	id: 123455,
            first: 'seo',
            last: 'tomas'
    }
    
    tomas.id = 423423 // ERROR - id is readonly

     

     

     

    Interface Method
    • 속성 뒤에 괄호를 사용하여 메소드임을 명시
    • 메소드의 반환 타입 지정 가능
    interface Person {
    	readonly id: number
            first: string
            last: string
            nickname?: string
            sayHi(): string
    }

     

     

    • Interface Method 파라미터
    interface Product {
    	name: string
        	price: number
            applyDiscount(discount: number): number
    }
    
    let newProduct: Product = {
    	name: 'snack',
            price: 500,
            applyDiscount (amount: number) {
                return 50
            }
    }

     

     

     

    Custom Type vs Interface
    • Interface 특징 - Merge
    • 동일한 이름의 Interface는 하나로 합쳐짐
    interface Dog {
    	name: string,
        	age: number
    }
    
    interface Dog {
    	breed: string,
        	bark(): string
    }
    
    // 인터페이스 객체 속성 합쳐짐
    interface Dog {
    	name: string,
            age: number,
            breed: string,
            bark(): string
    }

     

     

    • Interface 특징 - Extends
    • extends를 사용하여 Interface를 상속받음
    interface Dog {
    	name: string,
            age: number,
            breed: string,
            bark(): string
    }
    
    interface ServiceDog extends Dog {
    	job: 'drug sniffer' | 'cuttie' | 'barking'
    }
    
    let newDog: ServiceDog = {
    	name: 'mark',
        	age: 3,
            breed: 'lab',
            bark: () => 'ooOnk!',
            job: 'cuttie'
    }

     

     

    • Interface 다중 상속
    • , 를 사용하여 상속받고자 하는 Interface들을 extends 뒤에 나열
    interface Human { name: string }
    interface Employee { readonly: id: number, email: string }
    
    interface Engineer extends Human, Employee = { age: number }
    
    let shj: Engineer = {
    	name: 'shj',
            id: 123456,
            email: 'test@email.com',
            age: 11
    }

     

     

    • Interfaces vs Custom Type
    Interfaces
    - extends 상속 가능
    - 오직 객체 타입만 생성
    - Interfaces Merge로 객체 속성 합치기 
    Custom Type
    - & 키워드로 객체 합치기
    - 리터럴 타입, 문자열 타입 등 모든 타입 선언 가능
    - 중복된 type 이름 불가

     

     

     

     

     

     

     

    'Typescript' 카테고리의 다른 글

    9. Let's do Mini Project  (0) 2022.10.21
    8. Typescript Configuring  (0) 2022.10.21
    6. Tuple & Enum  (0) 2022.10.18
    5. Union Type  (0) 2022.10.17
    4. Array Type  (0) 2022.10.17
Designed by Tistory.