[TypeScript] Interface(2)

haryun·2022년 9월 7일
0

TypeScript

목록 보기
2/6
post-thumbnail

패스트캠퍼스 TypeScript 강의 Ch 5. Interfaces 복습 내용
참고링크

📕 Interface 정리

📌 인터페이스 확장하기

interface Dog {
  color: string;
  age: number;
}

interface Kamma extends Dog {
  isCute: boolean;
}

const myPuppy: Kamma = {
  color: 'brown',
  age: 12,
  isCute: true
};

extends 키워드를 사용하여 인터페이스의 확장(상속)이 가능하며 ,를 통해 다중요소로부터의 확장도 가능하다.

📌 함수를 인터페이스로 만들기

interface HelloPerson {
  (name: string, age?: number): void;
}

const helloPerson: HelloPerson = function(name: string) {
  console.log(`안녕하세요! ${name} 입니다.`);
};

helloPerson('Haryun', 25); // helloPerson() 선언시 두번째 매개변수를 지정하지 않았으나 정상 작동함

helloPerson() 함수 실행시 함수를 선언하여 실행내용을 작성한 부분보다 기존 인터페이스의 형태를 우선하여 따른다.

const helloPerson: HelloPerson = function(name: string, age: number) {
  console.log(`안녕하세요! ${name} 입니다.`);
}; // error

인터페이스 HelloPerson은 age를 선택적 속성으로 지정하였으나, 해당 구문에서는 기본 속성으로 지정하였기 때문에 기존 인터페이스 형식과 맞지 않아 오류가 발생한다. (age?: number로 수정시 정상작동)

📌 Readonly property

interface Dog {
  name: string;
  age: number;
  readonly color: string;
}

const myPuppy: Dog = {
  name: 'Komma',
  age: 4,
  color: 'Black'
}

myPuppy.color = 'white'; //error

속성명 앞에 readonly 키워드를 작성하여 해당 속성을 읽기전용으로 지정한다.
readonly 사용시 초기화는 가능하지만 값의 재할당은 불가능하다. (type에서도 동일하게 사용이 가능하다)

📌 type alias와 interface 비교하기

// 1. function 표현
type EatType = (food: string) => void;
interface IEat {
  (food: string): void;
}

// 2. Array 표현 
type PersonList = string[];
interface IPersonList {
  [index: number]: string; //-> indexable type 
}

// 3. intersection (& 기호를 통해 여러 타입을 합쳐서 사용할 수 있음)
interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}
interface ArtistsData {
  artists: { name: string }[];
}
type ArtistsResponseType = ArtistsData & ErrorHandling;
interface IArtistResponse extends ArtistsData, ErrorHandling {};

let art: ArtistsResponseType;
let iar: IArtistResponse;

// 4. Union Type (변수나 함수의 매개변수에 두가지 이상의 타입을 지정하여 사용하며 |를 통해 구분, 값이 지정된 타입 중의 하나가 될 수 있음)
interface Bird {
  fly(): void;
  layEggs(): void;
}
interface Fish {
  swim(): void;
  layEggs(): void;
}
type PetType = Bird | Fish; // => extends, implements 불가

// 5. Declaration Merging (type alias는 사용 불가)
interface MergingI {
  a: string;
  b: number;
}
interface MergingI {
  c: string;
}
let merging: MergingI; // 동일한 이름의 인터페이스는 합쳐짐

type alias는 타입의 이름을 지정하는 방식이고, interface는 새로운 형태의 타입을 정의하는 것이라고 구분지어 생각해야 한다.

0개의 댓글