Typescript #2 - Interface

Fstone·2020년 12월 8일

Typescript

목록 보기
2/3
post-thumbnail

Interface

  • 변수, 함수, class의 속성과 속성의 type을 정의한 객체이다.
  • 속성 method도 가질 수 있지만 추상 method로 부모 interface를 참조하는 자식 객체에서 반드시 구현되어야 한다.
  • class와 비슷하지만 instance를 직접 생성할 수 없다.

interface type 정의

  • 변수
interface User {
  id: number;
  name: string;
  email: string;
}

const user: User = {
  id: 1,
  name: "fstwon",
  email: "velog.io/@fstone"
}
  • 함수 parameter
interface User {
  (id: number, name: string, email: string);
}

const func: User = (id, name, email) =>{
  console.log(id, name, email)
}

console.log(func(1, "fstwon", "velog.io/@fstone"); 
// 1, fstwon, velog.io/@fstone
  • class property

    • class 접근 제한자: 부모 class와 자식 class와 자식 class의 instance에서 속성과 method 접근 가능 여부를 정의한다.

      • public: 부모, 자식 class와 자식 class의 instance에서 모두 속성과 method를 사용할 수 있다.

      • private: 속성과 method가 정의 된 class에서만 접근이 가능하다.

      • protected: 부모, 자식 class에서 속성과 method를 사용할 수 있지만 자식 class의 instance에서는 접근할 수 없다.

      • readonly: 자식 class에서 속성은 읽기만 가능하고 변경할 수 없다.

interface User {
  id: number;
  name: string;
  email: string;
}

class Userinfo implements User {
  constructor(public id: number, public name: string, public email: string) {}
}

console.log(new Userinfo(1, "fstwon", "velog.io/@fstone"));
// Userinfo { id: 1, name: 'fstwon', email: 'velog.io/@fstone' }

Reference

https://www.typescriptlang.org/docs/handbook/intro.html

0개의 댓글