TypeScript 설치 이유

TypeScript를 적용하지 않았을 경우에, 아래와 같은 코드를 실행할 수 있다.

const something = 'Hello'
const result = Math.long(something)
console.log(result)
NaN

NaN 이라는 숫자가 아니라는 결과가 출력되는데, TypeScript를 적용하게 되면, 잘못된 것들을 수정할 수 있다.

TypeScript 설치

npm install --save-dev typescript

package.json에 들어가면 아래와 같이 의존성이 적용된 걸 볼 수 있다.

{
  "scripts": {
    "test": "echo \"Hello, world!\" && exit 1"
  },
  "devDependencies": {
    "eslint": "^8.47.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-config-prettier": "^9.0.0",
    "eslint-plugin-import": "^2.28.0",
    "eslint-plugin-node": "^11.1.0",
    "prettier": "^3.0.1",
    "typescript": "^5.1.6"
  }
}

TypeSciprt 적용

// @ts-check
const something = 'Hello'
const result = Math.long(something)
console.log(result)

와 같이 // @ts-check를 적게 되면, something 부분에 에러가 나는 것을 확인할 수 있다.

Node.js에서 TypeScript 적용

npm install --save-dev @types/node

package.json에 가면 의존성이 적용되어 있는 걸 확인할 수 있다.

{
  "scripts": {
    "test": "echo \"Hello, world!\" && exit 1"
  },
  "devDependencies": {
    "@types/node": "^20.4.10",
    "eslint": "^8.47.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-config-prettier": "^9.0.0",
    "eslint-plugin-import": "^2.28.0",
    "eslint-plugin-node": "^11.1.0",
    "prettier": "^3.0.1",
    "typescript": "^5.1.6"
  }
}

@types/nodeNode.js에서 필요한 파일의 타입들을 정해주는 역할을 한다.
main.js를 다음과 같이 작성한다.

// @ts-check
// Formatting: Prettier, Type Checking
// Linting: ESLint

const http = require('http')

const server = http.createServer((req, res) => {
  res.statusCode = -200
  res.end('Hello World!')
})

const PORT = 3000
server.listen(PORT, () => {
  console.log(`The Server is listening at PORT: ${PORT}.`)
})

실행시킨다.

node main.js

다음과 같은 결과가 나오게 된다.

The Server is listening at PORT: 3000.

main.js를 작성하면서 오타 혹은 잘못된 타입을 넣었을 경우, 바로 알 수 있게 해준다.

TypeScript 설정

jsconfig.json 이라는 파일을 생성 후, 다음과 같은 코드를 작성한다.

{
  "compilerOptions": {
    "strict": true
  },
  "include": ["src/**/*"]
}

compilerOptions에서 strict는 엄격하게 검사를 하는 것을 의미하고, include는 범위를 의미한다.
tsconfig 공식 도큐먼트에서 조금 더 명확하게 알 수 있다.

'JavaScript > Node.js' 카테고리의 다른 글

Express 설치  (0) 2023.08.13
ESLint 설치  (0) 2023.08.12
prettier 설치  (0) 2023.08.12
package.json  (0) 2023.08.12
server.js  (0) 2023.08.12

+ Recent posts