
npm i -D typescript // -D는 ts가 devDependencies에 설치된다
touch tsconfig.json
// tsconfig.json { "include": ["src"], "compilerOptions": { "outDir": "", // 자바스크립트 파일이 생성될 디렉터리를 지정한다 "target": "ES6" // js로 build할때 버전을 의미한다 } } // package.json "scripts": { "build": "tsc" }
class Block { constructor(private data: string) {} static hello() { return "hi"; } }//build한 결과 class Block { constructor(data) { this.data = data; } static hello() { return "hi"; } }
lib이란?
// tsconfig.json { "include": ["src"], "compilerOptions": { "outDir": "", // 자바스크립트 파일이 생성될 디렉터리를 지정한다 "target": "ES6", // js로 build할때 버전을 의미한다 "lib": ["ES6", "DOM"] // es6을 지원하는 환경에서 실행될것이다, 브라우저 위에서 실행한다 } }
DOM을 넣는 이유는? ts파일에서 document.이렇게 작성하면 이게 뭔지 알 수 있다.
즉, DOM을 사용하면 ts는 document, window 등이 가지고 있는 모든 이벤트와 메소드를 보여준다
예) document.querySelector() 사용가능
//myPackage.js export function init(confing) { return true; } export function exit(code) { return code + 1; }//index.ts // 정의파일을 따로 설정해지 않은 처음 상태에서는 오류가 난다 import { init } from "myPackage"; init({ url: "true" })//myPackage.d.ts // ts에게 myPackage를 설명해주는 정의파일 // 이렇게 작성하고 나면 index.ts에서는 오류가 더이상 나지 않는다 interface Config { url: string; } declare module "myPackage" { function init(config: Config): boolean; }
// @ts-check /** * Initializes the project * @param {Object} config //입력값의 데이터타입은 객체, 입력값의 이름은 config * @param {boolean} config.debug // boolean타입은 config.debug안에 들어있을것이다 * @param {string} config.url // config.url 타입 * @returns boolean */ export function init(config) { return true; } /** * Exits the program * @param {number} code * @returns number */ export function exit(code) { return code + 1; }