JavaScript의 한계를 TypeScript가 보완한 상위 집합(Superset) 언어로 JS에 정적타입 검사와 클래스 기반 객체지향프로그래밍 등의 기능을 추가하여 개발된 언어로, JS가 발전하면서 생긴 단점을 보완하기 위해 등자앟게 되었다.
1. 프로젝트 폴더 생성
mkdir [typescript-exam] // [폴더 명]
2. 생성한 프로젝트 폴더로 이동, 터미널에서 명령어를 실행하여 새로운 프로젝트를 초기화
cd [typescript-exam] // [폴더 명]
npm init -y
3. 프로젝트 내부에서 npm
을 사용할 수 있으므로 TypeScript를 설치한다.
npm install typescript --save-dev
4. 프로젝트 root 디렉토리에 tsconfig.json
파일을 생성하고 아래의 내용을 입력한다
아래 내용을 입력하면 src
폴더에 typescript언어로 된 파일을 작성할 수 있다.
//compilerOptions 내의 속성은 자유롭게 커스텀 가능
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"outDir": "./dist"
},
"include": [
"src/**/*"
]
}
VSCode 에디터에서 ESLint 확장 프로그램 설치
VSCode 에디터에 아래 설정 적용하기
cmd + shift + p
로 setting.json 파일 찾기
{
// ...
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.alwaysShowStatus": true,
"eslint.workingDirectories": [
{"mode": "auto"}
],
"eslint.validate": [
"javascript",
"typescript"
],
}
위 내용은 사용자 설정에 넣어야 하는데 기존에 설치한 확장 프로그램들이 있다면 이미 다른 설정들이 작성되어 있을 수 있다. 채워져 있는 경우 기존 코드 아래에 내용을 입력해 준다.
format on save
가 설정되어있는 지 확인한다.cmd + ,
Prettier 확장 프로그램 설치
몇가지 필요한 프리셋과 라이브러리 설치
npm i -D @babel/core @babel/preset-env @babel/preset-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint prettier eslint-plugin-prettier
.eslintrc.js
파일을 만들고 아래의 내용을 입력module.exports = {
root: true,
env: {
browser: true,
node: true,
jest: true,
},
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
plugins: ['prettier', '@typescript-eslint'],
rules: {
'prettier/prettier': [
'error',
{
singleQuote: true,
tabWidth: 2,
printWidth: 80,
bracketSpacing: true,
arrowParens: 'avoid',
},
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'prefer-const': 'off',
},
parserOptions: {
parser: '@typescript-eslint/parser',
},
};
위 파일 내부에는 prettier
와 typescript-eslint
에 대한 설정, react를 위한 설정이 되어 있다.
rules
내에 작성된 코드는 옵션이다.
interface Student {
id: number;
name: string;
}
const greetingStudent = (user: Student) => {
console.log(`Hello, ${user.name}!`);
}
const student1 = {
id: 1,
name: "kimcoding"
}
greetingStudent(student1);
설명 |
---|
1. 정적 타입 검사 기능을 제공, 코드의 가독성 및 유지 보수성을 높여준다. |
2. 기존 JavaScript는 함수와 변수의 타입을 명시적으로 지정하지 않아도 동작하는 경우가 많았고, 그 부분을 보완하여 런타임 에러를 최소화 시킨다. |
3. Class, Interface 등의 기능을 제공하여 객체지향 프로그래밍을 보다 쉽게 할 수 있도록 도와준다. |