CRA를 사용하지 않고 타입스크립트 프로젝트를 생성하기
콘솔창에
npm init -y
를 입력, package.json 파일 생성npm i -D typescript
입력, devDependency에 타입스크립트 추가타입스크립트 설정 파일 tsconfig.json 생성
이 파일을 통해 vscode는 TS로 작업하는 것을 감지하고 자동완성을 제공한다.
{ /* Directories for compiled JS */ "include":[ "src" ], "compilerOptions":{ "outDir" : "build", /* Product will be located at */ "target":"ES6", /* Product will be compiled in ES6 */ "lib": ["ES6", "DOM"] /* Describe runtime env(platform) */ /* then, TS will help you with auto-complete*/ /* ex) documnet.querySelector */ } }
대부분은 definitelyTyped에서 찾지만, 공부를 위해서 직접 declaration을 한다면
- type definition file(d.ts) 을 통해 타입 정의를 따로 해줄 경우.
/// myPackage.js export function init(config) { return true; } export function exit(code) { return code + 1; }
/// index.ts 에 이렇게 import 하려면 import { init, exit } from "myPackage"; /// Could not find a declaration file for module 라는 에러가 뜬다.
/// myPackage.d.ts 파일을 생성 /// 아래와 같이 declaration을 선언한다. interface Config { debug: boolean; url: string; } declare module "myPackage" { function init(config: Config): boolean; function exit(code: number): number; }
프로젝트 안에 js, ts가 같이 존재하는 경우에는 tsconfig에
allowJs:true
로 설정해준 후 JS파일을 import 하면 된다.JS를 그대로 사용하되, 타입스크립트의 보호를 받으려면 JSDoc을 활용할 수 있다. 이 경우 주석을 활용해 type 보호를 받을 수 있다.
// JSDoc 코멘트를 활용해 타입보호를 받을수 있다. // @ts-check /** * initailizes the project * @param {object} config * @param {boolean} config.debug * @param {string} config.url * @returns {boolean} */ export function init(config) { return true; } /** * Exits the program * @param {number} code * @returns */ export function exit(code) { return code + 1; }
'개발 > 자바스크립트' 카테고리의 다른 글
타입스크립트 angle brackets, 꺾쇠 괄호 <> (1) | 2022.09.28 |
---|---|
Framer-motion 리액트 애니메이션 라이브러리 (2) | 2022.09.23 |
[타입스크립트] Call Signatures (0) | 2022.08.09 |
자바스크립트의 비동기 처리 (0) | 2022.07.12 |
null undefined의 차이 (0) | 2022.05.16 |