TypeScript-Interface

이수민·2022년 10월 26일
0

[TS]TypeScript

목록 보기
1/1

Interface 활용

: 두개의 시스템 사이에 정의한 약속 혹은 규칙을 포괄

TypeScript Interface 범주

✬ 객체의 스펙(속성과 속성의 타입)
✬ 함수의 파라미터
✬ 함수의 스펙
✬ 배열과 객체 접근 방식
✬ 클래스

Interface 예시

// Interface 이름은 대문자
interface Human {
  name: string;
  age: number;
  talk(): void;
}

// interface 자체를 타입으로 객체 생성
const tom: Human = {
  name: 'tom',
  age: 10,
  talk: () => console.log("Hello I'm tom"),  
};

tom.talk(); // Hello I'm tom

Interface 와 Type

  • Interface extends 혹은 Implement를 통한 확장 가능
  • type의 경우, and로 묶어 확장 가능
    -> type Cat= { age: string }, type Bird = { height: number}
    --> type Animal = Cat & Bird
  • 비슷한 형태지만 좀 더 확장에 용이한 Interface를 사용하는 좋은 사용

선택적 Property

: Interface에 정의된 모든 속성을 사용하지 않을 수 있도록 '?'연산자를 통해 선택적 Property를 제공한다.

interface Human {
  name: string
  footSize?: number
}

const top: Human = { name: 'tom' };

? 가 붙은 속성의 경우, 있을수도 있고 없을수도 있다.

0개의 댓글