[TypeScript] type과 interface

김지훈·2024년 4월 26일
0

TypeScript 스터디

목록 보기
2/10
post-thumbnail

1. type

type은 타입의 별칭을 지정하는 키워드이며, 아래와 같이 사용할 수 있다.

type Point = {
  x: number;
  y: number;
};

function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });

type을 사용하면 객체 타입뿐만 아니라, 모든 타입에 대하여 새로운 이름을 부여할 수 있다. 예를 들어, 아래와 같이 유니언 타입에 대하여 타입 별칭을 부여할 수도 있다.

type ID = number | string;

type을 사용하여도 동일 타입에 대하여 각기 구별되는 것은 아님을 유의해야 한다.

type Name = string;
let _name: Name = 'jihun';

function greet(str: string) {
    console.log(`Hello, I'm ${str}`);
}

greet(_name); // 성공. string과 Name 사이 구분 없음

2. interface

interface는 객체 타입을 정의하는 키워드이다. 아래 코드는 type을 사용한 경우와 마찬가지로 동작한다.

interface Point {
  x: number;
  y: number;
}
 
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });

3. typeinterface의 차이

typeinterface는 매우 유사하며, 대부분의 경우 둘 중 하나를 자유롭게 선택하여 사용할 수 있지만 몇 가지 차이점이 존재한다.

  1. type과 달리 interface는 객체 타입 외의 타입은 직접적으로 사용할 수 없다.
type MyType = string | number; // 가능
interface MyInterface {
    string | number;
} // 불가능
  1. interfaceextends를 사용하여 확장할 수 있지만, type은 교집합을 사용해야 한다.
interface MyInterface {
    oldInter: string
}
interface NewInterface extends MyInterface {
    newInter: number
}

type MyType = {
    oldType: string
}
type NewType = MyType & {
    newType: number
}
  1. interface는 중첩하여 정의할 수 있다. 즉, 아래와 같은 방식으로 새 필드를 추가할 수 있지만, type은 정의된 이후 수정할 수 없다.
interface MyInterface {
    oldInter: string
}
interface MyInterface {
    newInter: number
} // 가능. MyInterface는 oldInter와 newInter를 가지게 된다.

type MyType = {
    oldType: string
}
type MyType = {
    newType: string
} // 불가능

0개의 댓글