개발 알다가도 모르겠네요

타입스크립트의 인터페이스 본문

웹/Typescript

타입스크립트의 인터페이스

이재빵 2022. 6. 18. 10:49
728x90

TypeScript는 인터페이스를 지원하는데 일반적으로 타입 체크를 위해 사용되며 변수, 함수, 클래스에 사용할 수 있습니다.

인터페이스 선언된 프로퍼티 또는 메소드의 구현을 강제하여 일관성을 유지할 수 있도록 하는 것입니다.

인터페이스는 프로퍼티와 메소드를 가질 수 있다는 점에서 클래스와 유사하나, 직접 인스턴스를 생성할 수 없고 모든 메소드는 추상 메소드입니다.

단, 추상 클래스의 추상 메소드와 달리 abstract 키워드를 사용하지 않습니다.

// 인터페이스의 정의
interface Todo {
  id: number;
  content: string;
  completed: boolean;
}

let todos: Todo[] = [];

// 파라미터 todo의 타입으로 Todo 인터페이스를 선언하였다.
function addTodo(todo: Todo) {
  todos = [...todos, todo];
}

// 파라미터 todo는 Todo 인터페이스를 준수하여야 한다.
const newTodo: Todo = { id: 1, content: 'typescript', completed: false };
addTodo(newTodo);
console.log(todos)
// [ { id: 1, content: 'typescript', completed: false } ]

인터페이스를 사용하여 함수 파라미터의 타입을 선언할 수 있습니다.

이때 해당 함수에는 함수 파라미터의 타입으로 지정한 인터페이스를 준수하는 인수를 전달해야 합니다.

함수에 객체를 전달할 때 복잡한 매개변수 체크가 필요없어서 매우 유용하게 쓰입니다.

 

 

함수와 인터페이스

인터페이스는 함수의 타입으로 사용할 수 있으며 이때 함수의 인터페이스에는 타입이 선언된 파라미터 리스트와 리턴 타입을 정의합니다.

// 함수 인터페이스의 정의
interface SquareFunc {
  (num: number): number;
}

// 함수 인테페이스를 구현하는 함수는 인터페이스를 준수하여야 한다.
const squareFunc: SquareFunc = function (num: number) {
  return num * num;
}

console.log(squareFunc(10)); // 100

 

클래스와 인터페이스

클래스 선언문의 implements 뒤에 인터페이스를 선언하면 해당 클래스는 지정된 인터페이스를 반드시 구현하여야 합니다.

인터페이스는 프로퍼티와 메소드를 가질 수 있다는 점에서 클래스와 유사하나 직접 인스턴스를 생성할 수는 없습니다.

// 인터페이스의 정의
interface ITodo {
  id: number;
  content: string;
  completed: boolean;
}

// Todo 클래스는 ITodo 인터페이스를 구현하여야 한다.
class Todo implements ITodo {
  constructor (
    public id: number,
    public content: string,
    public completed: boolean
  ) { }
}

const todo = new Todo(1, 'Typescript', false);

console.log(todo);

 

모든 메소드는 추상 메소드이어야 하며 인터페이스를 구현하는 클래스는 인터페이스에서 정의한 프로퍼티와 추상 메소드를 반드시 구현해야 합니다.

// 인터페이스의 정의
interface IPerson {
  name: string;
  sayHello(): void;
}

/*
인터페이스를 구현하는 클래스는 인터페이스에서 정의한 프로퍼티와 추상 메소드를 반드시 구현하여야 한다.
*/
class Person implements IPerson {
  // 인터페이스에서 정의한 프로퍼티의 구현
  constructor(public name: string) {}

  // 인터페이스에서 정의한 추상 메소드의 구현
  sayHello() {
    console.log(`Hello ${this.name}`);
  }
}

function greeter(person: IPerson): void {
  person.sayHello();
}

const me = new Person('Lee');
greeter(me); // Hello Lee

 

선택적 프로퍼티

인터페이스의 프로퍼티는 반드시 구현되어야 하지만 인터페이스의 프로퍼티가 선택적으로 필요한 경우가 있을 수 있습니다.

선택적 프로퍼티(Optional Property)는 프로퍼티명 뒤에 ?를 붙이며 생략하여도 에러가 발생하지 않습니다.

interface UserInfo {
  username: string;
  password: string;
  age?    : number;
  address?: string;
}

const userInfo: UserInfo = {
  username: 'ungmo2@gmail.com',
  password: '123456'
}

console.log(userInfo);

 

인터페이스 상속

interface Person {
  name: string;
  age?: number;
}

interface Developer {
  skills: string[];
}

interface WebDeveloper extends Person, Developer {}

const webDeveloper: WebDeveloper =  {
  name: 'Lee',
  age: 20,
  skills: ['HTML', 'CSS', 'JavaScript']
}

' > Typescript' 카테고리의 다른 글

타입스크립트의 Enum  (0) 2022.06.19
타입스크립트의 함수  (0) 2022.06.18
타입스크립트의 제네릭  (0) 2022.06.18
타입스크립트의 Class  (0) 2022.06.17
타입스크립트란 무엇인가?  (0) 2022.06.17