Notice
Recent Posts
Recent Comments
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Link
관리 메뉴

개발블로그

TypeScript - Interface 본문

TypeScript

TypeScript - Interface

춘식스 2022. 5. 26. 18:31
클래스 또는 객체를 위한 타입을 지정 할 때 사용되는 문법이다.
  • 클래스에서 interfaceimplements하기
    • 클래스를 만들 때, 특정 조건을 준수해야 함을 명시하고 싶을 때 interface를 사용하여 클래스가 가지고 있어야 할 요구 사항을 설정
    • 클래스를 선언 할 때 implements 키워드를 사용하여 해당 클래스가 특정 interface의 요구사항을 구현한다는 것을 명시
// Shape 라는 interface를 선언
interface Shape {
  getArea(): number;
  // Shape interface 에는 getArea 라는 함수가 꼭 있어야 하며 해당 함수의 반환값은 숫자이다.
}

class Circle implements Shape {
  // 'implements' 키워드를 사용하여 해당 클래스가 Shape interface 의 조건을 충족하겠다는 것을 명시

  radius: number; // 멤버 변수 radius 값을 설정

  constructor(radius: number) {
    this.radius = radius;
  }

  // 너비를 가져오는 함수를 구현
  getArea() {
    return this.radius * this.radius * Math.PI;
  }
}

class Rectangle implements Shape {
  width: number;
  height: number;
  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }
  getArea() {
    return this.width * this.height;
  }
}

const shapes: Shape[] = [new Circle(5), new Rectangle(10, 5)];

shapes.forEach(shape => {
  console.log(shape.getArea());
});

컴파일 후 실행 결과


  • 일반 객체를 interface로 타입 설정하기
  • 일반 예시
interface Person {
  name: string;
  age?: number; // 물음표 = 설정을 해도 되고 안해도 되는 값이라는 것을 의미
}
interface Developer {
  name: string;
  age?: number;
  skills: string[];
}

const person: Person = {
  name: '김사람',
  age: 20
};

const expert: Developer = {
  name: '김개발',
  skills: ['javascript', 'react']
};
  • 형태가 유사하면 interface를 선언 할 때 다른 interfaceextends해서 상속 받을 수 있다.
interface Person {
  name: string;
  age?: number;
}
interface Developer extends Person {
  skills: string[];
}

const person1: Person = {
  name: '김사람',
  age: 20
};

const expert1: Developer = {
  name: '김개발',
  skills: ['javascript', 'react']
};

const people: Person[] = [person1, expert1];

  • readonly
    • 일기 전용 속성이다.
    • 처음 생성 할때만 수정 가능하다.
    • 나중에는 수정 불가능하다.
interface User {
  name: string;
  age: number;
  gender?: string;
  readonly birthYear: number;
  // readonly = 읽기 전용 속성이라 처음 생성 할때만 수정 가능 -> 나중에 수정이 안된다.
}

let user: User = {
  name: 'xx',
  age: 30,
  birthYear: 2000
}

user.name = 'bb',
user.age = 10,
user.birthYear = 1990 // Error

console.log(user.age);

  • interface와 함수
interface Add {
  (num1 : number, num2 : number): number;
}

const add2 : Add = function(x, y) {
  return x + y;
  // (x, y) == (num1, num2)
  // 다르게 적어줘도 잘 인식한다.
}

add2(10, 20);

interface IsAdult {
  (age: number): boolean;
}

const a5: IsAdult = (age) => {
  return age > 19;
}

// age 타입을 number로 했고 age가 33일때 19보다 크니
// 불리언타입으로 true가 나온다.

a5(33) // true

'TypeScript' 카테고리의 다른 글

TypeScript - Generics  (0) 2022.05.27
TypeScript - Type Alias  (0) 2022.05.27
TypeScript 함수  (0) 2022.05.26
TypeScript 기본문법  (0) 2022.05.26
TypeScript 초기설정  (0) 2022.05.24
Comments