[TypeScript] Interface란?

LMH·2023년 4월 5일
0
post-thumbnail

Interface

TypeScript 인터페이스(Interface)는 객체의 구조를 정의하는 데 사용되는 개념입니다. 인터페이스는 다음과 같은 형식으로 작성됩니다:

interface SomeInterface {
  prop1: string;
  prop2: number;
  prop3?: boolean;
}

위의 코드에서 SomeInterface는 인터페이스의 이름이며, 인터페이스 안에는 prop1, prop2, prop3와 같은 속성이 정의됩니다. 각 속성은 이름과 타입을 갖고 있으며, 선택적으로 존재할 수 있습니다(prop3?).

인터페이스를 사용하면 다른 객체에서 해당 인터페이스의 속성을 구현할 수 있습니다. 이를 통해 코드를 더욱 유연하게 만들 수 있습니다. 예를 들어, 다음과 같이 인터페이스를 구현할 수 있습니다:

interface SomeInterface {
  prop1: string;
  prop2: number;
  prop3?: boolean;
}

class SomeClass implements SomeInterface {
  prop1: string = "foo";
  prop2: number = 42;
}

위의 코드에서 SomeClass는 SomeInterface를 구현하는 클래스입니다. 클래스 안에는 prop1, prop2, prop3와 같은 속성이 정의될 필요가 없습니다. 대신, prop1, prop2 속성은 반드시 구현되어야 합니다.

인터페이스는 또한 함수의 매개변수나 반환값에 대한 타입을 정의할 때도 사용될 수 있습니다. 예를 들어, 다음과 같이 인터페이스를 사용하여 함수의 매개변수와 반환값을 정의할 수 있습니다:

interface SomeInterface {
  (arg1: string, arg2: number): boolean;
}

function someFunction(arg1: string, arg2: number): boolean {
  // ...
}

const someVariable: SomeInterface = someFunction;

위의 코드에서 SomeInterface는 함수 타입의 인터페이스입니다. 이 인터페이스는 두 개의 매개변수(arg1과 arg2)를 갖고, boolean 값을 반환합니다. someFunction 함수는 SomeInterface를 구현하므로 someVariable에 할당될 수 있습니다.

profile
새로운 것을 기록하고 복습하는 공간입니다.

0개의 댓글