타입스크립트 선언 파일

movie·2022년 7월 11일
1

들어가기전,,

  • 타입스크립트 파일에 변수를 선언하면 자동으로 ambient module이 된다. (import와 export)를 하지 않아도 타입스크립트 파일끼리는 변수를 가져다 쓸 수 있다.
// test1.ts

let movie;
// test2.ts

let movie; 
// error : 블록 범위 변수 'movie'을(를) 다시 선언할 수 없습니다.ts(2451)

ambient
구현을 정의하지 않은 선언 (일반적으로 d.ts파일에 정의되어 있다.)

local module

  • 로컬 모듈로 사용하려면 import{} 혹은 export{} 하나를 써주어야 한다.
  • 로컬 모듈에서 글로벌 변수로 만들고 싶을 때는 아래와 같이 해주면 된다.
// d.ts
export {}; // local module

declare global {
  interface Post {
    id: number;
    title: string;
    localDate: {
      date: string;
      time: string;
    };
    content: string;
  }
}
// 모든 파일에서 Post 타입을 쓸 수 있음. 

// ambient module
interface Post {
  id: number;
  title: string;
  localDate: {
    date: string;
    time: string;
  };
  content: string;
}
// 그냥 이렇게 써도 모든 파일에서 Post 타입을 쓸 수 있음. 


d.ts

  • 타입스크립트 선언 파일 : d.ts
  • 타입스크립트 코드의 타입 추론을 돕는 파일

언제 사용할까?

  • 타입스크립트를 지원하지 않는 자바스크립트 라이브러리를 타입스크립트에서 사용하고 싶을 경우
    • 만약 타입 선언 파일이 존재하지 않는다면, 모듈 '--'에 대한 선언 파일을 찾을 수 없습니다. '--.js'에는 암시적으로 'any' 형식이 포함됩니다.ts(7016) 타입스크립트 에러가 뜬다.
    • npm에서 다운받은 @types/가 붙은 모듈은 타입 선언만 포함된 모듈이다.
  • 커스텀 타입을 사용하고 싶은 경우


d.ts 작성법

1️⃣ : module 키워드

  • module 키워드와 따옴표로 묶인 이름을 이용해 추후 import될 수 있는 모듈을 선언할 수 있다.
// module.d.ts
declare module '@/test/module.js' {
  const testModule = (message: string) => {};

  export default testModule;
}

// module.js
const testModule = message => {
  console.log(message);
};

export default testModule;

// 사용하는 곳 
import testModule from '@/test/module.js';

testModule(`hi`);

2️⃣ : namespace

  • 일종의 패키지 개념
  • 클래스, 인터페이스, 함수 등을 한 파일에서 그룹화
// module.d.ts
declare module '@/test/module.js' {
  namespace testNamespace {
    function test1(message: string): string;
  }

  export default testNamespace;
}

//module.js
const testNamespace = {
  test1: message => {
    return message;
  },
};

export default testNamespace;

// 사용하는 곳
import testNamespace from '@/test/module.js';

console.log(testNamespace.test1('hi'));

3️⃣ : 기존 모듈에 추가하기

// d.ts 
import '@emotion/react'; // 기존 모듈 import

declare module '@emotion/react' {
  interface Theme {
    colors: {
      main: string;
      sub: string;
      gray_100: string;
      gray_200: string;
      gray_300: string;
      red_100: string;
    };
  }
} // custom

exercise

declare

  • 컴파일러에게 해당 변수나 함수의 존재 여부를 알린다.

export =

  • commonJS나 AMD에서 일반적으로 사용하는 import, export 형태를 지원하기 위해 사용
    • EX ) export = React


참고

profile
영화보관소는 영화관 😎

0개의 댓글