> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined-1/react-with-typescript/type-script/2./2.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 2) 객체 타입과 정의방법

인터페이스에 대해 알아볼 페이지

## 1. Object Type

* 객체의 속성명과 그 값의 타입을 묶어서 정의한 것을 객체 타입이라고 합니다.

```typescript
const user = {
  name: "홍길동",
  age: 30
};

let user :{name:string, age:number}; // 객체리터럴 타입
```

## 2. Type Aliases

* 길고 복잡한 **함수타입, Union 타입 혹은 객체타입** 에 별칭을 추가하여 **가독성**과 **재사용성**을 높이는 기능

```
//타입별칭 없이 변수를 사용하는 경우
function print(person:{name:string,age:number, gender?:string, interest?:string,}{
    가독성 x , 재사용성 x
}
// 타입별칭을 사용는경우
type Person = {name:string,age:number, gender?:string, interest?:string,}
function print(person:Person){

}
```

***

## 3. Interface

인터페이스는 타입스크립트에서 **객체의 구조를 정의하는 문법**입니다.  문법은 타입별칭비슷한 구조를 가지고 있습니다.

**ex)**

```typescript
interface Animal {
  name: string;
  kind: string;
  birth?: Date;
}

type AnimalAliases = {
  name: string;
  kind: string;
  birth?: Date;
}
```

***

## 4. Interface Vs Type Aliases

객체의 구조를 정의하는 두 방식간의 차이점은 **확장성(extendable)**&#xC785;니다. 확장성은 이미 **정의된 객체의 구조를 얼마나 자유롭게 수정할 수 있는지**를 의미합니다. &#x20;

### 1) Interface의 확장방법

**a. extends**&#x20;

기본적으로 인터페이스는 **확장**에서 자유롭습니다. 확장이라 함은 새로운 속성과 타입들이 추가됨을 의미합니다. 인터페이스를 확장할때는 **extends** 키워드를  사용합니다. &#x20;

```typescript
interface Employee extends Person {
    //Employee는 Person의 타입을 확장
    emp_id : number;
    dept_code : number;      
}
```

**b. 인터페이스 재정의를 통한 확장(Declaration Merging)**

인터페이스는 **선언 병합**(**Declaration Merging)**&#xC774;라는  독특한 방식으로 속성을 확장할 수 있습니다.

**선언 병합**은 이미 선언한 인터페이스를 재선언하여 **두 인터페이스의 속성을 하나로 합치는(merge) 기능**을 의미합니다.

```typescript
interface Student {
    name : string
}

// 선언 병합
interface Student {
    score : number
}


```

### 2) Type Aliases의 확장방법

타입 별칭으로 선언된 객체도 interface처럼 객체구조를 확장할 수 있습니다.  타입별칭은 extends나 선언병합이 아닌 **집합연산자를** 통해 속성을 확장합니다.

#### a. 합집합(Union) 연산자 ( | )

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2Ffq2GIL0BxIojfXyElNKT%2Fimage.png?alt=media&amp;token=80f84cb8-08fb-409a-bac1-2a50b0c3ee63" alt="" width="134"><figcaption></figcaption></figure>

|는 Union Type을 만들 떄 사용했던 **합집합(Union)연산자** 입니다. 합집합 연산자는 Type Aliases에서도 사용 가능합니다.&#x20;

```typescript
type A = string | number;
```

#### b. 교집합(Intersection) 연산자(&)

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2Fg0LTmmDxJjWfo641ik5L%2Fimage.png?alt=media&amp;token=902bd507-302e-46da-abea-0253604a663d" alt="" width="134"><figcaption></figcaption></figure>

& 연산자는 객체 타입별칭의 속성들을 하나로 합쳐주기 위해 사용하는 **교집합(Intersection)연산자** 입니다.&#x20;

```typescript
type B = {name:string} & {age : number};
// B == {name:string, age : number}
```

***

## 5. 결론

두 방법 모두 **객체의 구조**를 표현하는데 유용하게 사용됩니다.&#x20;

**그럼 객체 데이터의 구조를 정의해야 할때 interface와 Type Aliases중 어느걸 사용하는게 좋을까요?**

대부분의 경우 어떤 것을 써도 큰 문제가 없지만, 목적과 객체의 구조에 따라 다음과 같은 기준으로 선택할 수 있습니다

### 1) Interface를 사용하는게 적합한 경우

* 객체의 구조를 명확하게 정의하고 싶을 때
* 클래스와 결합해 implements로 사용하고 싶을 때
* 여러 **interface를 병합하거나 확장**해야 할 때
* 디버깅 시 <mark style="color:purple;">**타입명을 명확히 표시**</mark>하고 싶을 때

### 2) Type Aliases를 사용하는게 적합한 경우

* `string | number`와 같은 <mark style="color:purple;">**유니언 타입**</mark>을 정의할 때
* **튜플, 함수 타입, 기본형**을 이름으로 래핑하고 싶을 때
* 여러 타입을 **묶거나 조합**해야 할 때
* **조건부 타입, 제네릭** 활용 등 **고급 타입 설계**를 할 때

### 3) 그외

* **객체 타입**이라면 기본적으로 **Interface를 먼저 고려**하세요.
* interface로 해결되지 않는 구조가 필요한 경우에만 type을 사용하는 것이 일반적인 권장 방식입니다.

***

## 6. 객체타입 추가 문법(인덱스 시그니쳐 )

* 객체의 **속성명**과 그 값의 **타입**을 **일반화하여 표현**하는 문법
* 객체의 정확한 속성명을 모르는 경우에 사용한다.

```typescript
interface UserAgeMap {
  [username: string]: number;
}

const ages: UserAgeMap = {
  alice: 30,
  bob: 25,
  charlie: 28,
};
```

## 7. 타입 호환성

타입 호환성이란 타입스크립트에서 **두 타입이 서로 대입 가능한지를 판단**하는 개념입니다. 타입 스크립트는 호환성 여부를 체크할 때 **구조적 타이핑**에 기반하여 호환가능 여부를 판단합니다. 이 구조적 타이핑의 특징으로 인해 <mark style="color:orange;">**모든 타입이 완전히 일치하지 않더라도 타입호환**</mark>이 가능합니다.

### 1) 구조적 타이핑

객체의 타입을 비교할때  **타입의** **이름이 아닌&#x20;**<mark style="color:blue;">**속성**</mark>**과&#x20;**<mark style="color:blue;">**타입**</mark>**으로 비교**하는 방식을 의미합니다.&#x20;

```typescript
type A = {
    name : string,
    age : number
}
type B = {
    name : string,
    age : number
}
const a:A = {name:'mkm',age:11}; 
const b:B = a;// 속석명과 타입이 일치함.
```

### 2) 명목적 타이핑

자바 , C언어는 **명목적 타이핑**을 통해 호환성 여부를 검사합니다. 명목적 타이핑이란 객체의 구조에 집중하는 것이 아닌 **클래스의 이름**이 같아야 호환됨을 의미합니다.

```java
public class A {
    int a;
}
public class B {
    int b;
}

A a = new A();
B b = a; // 호환 불가. 클래스명이 다름.
```
