---
# System prepended metadata

title: Why use Type and not Interface in TypeScript

---

# Why use Type and not Interface in TypeScript

## extends

```typescript=
// type
type Me = {
    name: string;
    age: number
}

type mom = Me & {
    role: string
}

// interface
interface Me {
    name: string;
    age: number
}

type mom extends Me {
    role: string
}
```


## Q1
interface 只能描述 object 屬性，type 卻可以描述所有屬性

```typescript=
type Me = string // 合法
interface Me = string // 會報錯

const jan: Me = 'Jan'
```

Q2
type 可以單獨宣告 union type，interface 不行

```typescript=
type Me = string | string[] // 合法
interface Me = string | string[] // 會報錯

const jan: Me = 'Jan'
```
Q3
type 可以更簡單的宣告 Utility Type

```typescript=
type UserProps = {
    name: string;
    age: number;
    createAt: Date;
}

type GuestProps = Omit<UserProps, 'name'> // {age: number; createAt: Date;}
interface GuestProps extends Omit<UserProps, 'name'> {} // 明顯更不美觀
```

Q4
type 可以輕易地使用 tuples

```typescript=
const arr = [1, '123']

type Arr = [number, string];
interface Arr extends Array<nuber|string> {
    0: number,
    1: string
}
```
Q5
type 在做擴展更為適合

```typescript=
type Obj = {
    name: string;
    age: number;
    createAt: {
        time: Date;
        size: string;
    }
}

const A = typeof Obj['createAt'] // {time: Date; size: string;}
```

Q6
interface 遇到同名的宣告，會自動合併，反觀 type，會報錯提醒你已經有重複的名字了

```typescript=
interface Person {
    name: string;
}

interface Person {
    age: number;
    tall: number
}

const me: Person = {
    name: '1',
} // 抱錯，因為 age 跟 title 沒寫

type Person {
    name: string;
}

type Person {
    age: number;
    tall: number
}
// 抱錯，Duplicate identifier 'Person'，不能夠重複名稱
```

參考影片:
https://www.youtube.com/watch?v=Idf0zh9f3qQ