[타입스크립트 #4] 타입 내보내기 / 가져오기

최훈오·2023년 11월 18일
0

데브코스

목록 보기
13/29
post-thumbnail

타입 내보내기 / 가져오기

내보내기

export interface Add {
  (a: number, b: number): number
}

export const add: Add = (a, b) => a + b

가져오기

import { Add } from "./myUtils"

const newAdd: Add = (x, y) => x + y
newAdd(1, 2)

하지만 가져올 때 데이터와 타입을 구분하기 위해 type키워드를 가져올때 붙여주면 보기 편리하다.

import { add } from "./myUtils"
import type { Add } from "./myUtils"

기본 내보내기

export interface Add {
  (a: number, b: number): number
}

export const add: Add = (a, b) => a + b

export default {
  name: 'My utils!',
  add,
}

기본 가져오기

import utils, { add } from "./myUtils"
import type { Add } from "./myUtils"

const a = utils.add(4, 7)

기본으로 가져올 경우 네임스페이스를 통해 접근해야 한다.

export namespace Utils {
  export interface Add {
    (a: number, b: number): number
  }
}

export const add: Utils.Add = (a, b) => a + b

export default {
  name: 'My utils!',
  add,
}
import { add } from "./myUtils"
import type { Utils } from "./myUtils"

const newAdd: Utils.Add = (x, y) => x + y
newAdd(1, 2)

내보낼 때 네임스페이스를 만드는 것도 가능하다.

이렇게 중복되는 이름을 방지하여 편리하게 사용이 가능하다. 하지만 최근에 타입스크립트의 버전이 올라가면서 네임스페이스의 중요성이 많이 떨어졌다고 한다.

0개의 댓글