이번에는 타입스크립트가 무엇이고, 왜 사용해야하는지, 그리고 자바스크립트와 어떤 관계가 있는지에 대해 살펴보는 시간이 되겠습니다.
📑목차
1. 타입스크립트(TypeScript)
1-1. 타입스크립트의 개념
1-2. 타입스크립트의 특징
1-3. 타입스크립트를 사용하는 이유
1-4. 자바스크립트 VS 타입스크립트2. 타입스크립트 문법
2-1. 타입스크립트 node의 런타임 환경
2-2. 타입스크립트 설정 파일 tsconfig.json
2-3. 타입스크립트 빌드(트랜스파일)3. 타입스크립트와 객체지향
3-1. 객체지향의 개념
3-2. 클래스와 인스턴스
3-3. 상속과 캡슐화
3-4. 추상화 && 다형성
서론
본문에 들어가기전 혹시 타입스크립트에 들어본 적이 있으실까요? 자바스크립트를 공부하셨거나, 프론트엔드 쪽에 관심이 있으시다면 본적이 있으실겁니다. 타입스크립트를 왜 사용해야하고, 타입스크립트는 자바스크립트와 어떤 관계가 있는지에 대해 알아보는 시간을 갖게 되실겁니다.

본론
1. 타입스크립트(TypeScript)
1-1. 타입스크립트의 개념
마이크로소프트에서 개발한 자바스크립트의 상위 언어로 타입 시스템을 도입하여 정적으로 타입검사를 지원합니다.
1-2. 타입스크립트의 특징
- 타입을 미리 정의할 수 있다.
- 정적타입 언어이다.
- 컴파일러 언어이다.
- 객체지향 프로그래밍을 지원하는 언어다.
1-3. 타입스크립트를 사용하는 이유
자바스크립트는 실행하기 전까지 에러를 알수가 없고 작업을할때 코드의 내용이 모호해진다. 예측할수 없는 오류 즉 코드의 내용에서는 파악이 힘들다. 대규모의 프로젝트를 진행할때 작업을 하면서 코드의 량이 증가할텐데 이런 번번히 발생하는 타입의 오류를 실행환경에서 테스트를 해야 알수 있기 때문에 코드를 수정할때 번번히 오류가 발생하는 문제를 극복하기 위해 타입스크립트가 개발된 것이고 타입스크립트를 사용해야하는 이유이기도 합니다.
1-4. 자바스크립트 VS 타입스크립트
자바스크립트와 타입스크립트의 관계에서 자바스크립트에서는 타입 검사 없이 컴파일하면서 실행중 오류가 발생하지만 타입스크립트는 자바스크립트를 기반으로 만들어진 상위 집합(Superset) 언어로, 자바스크립트 문법을 그대로 사용하면서 여기에 정적 타입 검사와 개발 편의 기능을 추가하여 더 안전하고 유지보수가 쉬운 코드를 작성할 수 있도록 도와주며, 작성된 타입스크립트 코드는 실행을 위해 자바스크립트로 컴파일되어 브라우저나 Node.js에서 실행됩니다.
2. 타입스크립트 문법
2-1. 타입스크립트 node의 런타임 환경
타입스크립트는 실행 언어가 아니기 때문에 Node.js는 타입스크립트 파일을 직접 실행할 수 없습니다. 이런 문제점을 해결하려면 타입스크립트로 작성된 파일을 자바스크립트 파일로 컴파일해야 node 환경에서 실행할 수 있기 때문입니다.
다음 예시를 들어서 설명해드리겠습니다.

index.ts 코드
// 원시타입
let message : string = "hello TypeScript";
let count : number = 123456;
let isActive :boolean = false;
let hash : string = "0xfeself"; // 진수는 숫자형 데이터가 맞다. 하지만 우리가 사용할대 많이 문자열로 사용한다.
let initValue : any = "123"; // 타입검사를 하지 않겠다 any 쓰지마라 이거 사용할거면 자바스크립트를 사용하게 좋다.
// any 타입검사를 할수 없는 경우가 생긴다.
// 모듈 시스템 라이브러리에서 타입의 모듈을 제공하지 않는 경우 진짜 불가피한경우 사용해라
let initValue2 : undefined = undefined;
let initValue3 : null = null;
let initValue4 : unknown = "123";
// any unknown 의 차이
// any는 무슨 값인지 아예 몰라. 완전 타입검사를 강력하게 풀었다.
// unknown 타입을 특정할수는 없는데 검사는 또 하고싶어 검증은 필요해
//
initValue = 1;
// unknown 값을 재할당할때 조건이 필요하다
// 조건문 이후에 사용을 해야한다.
if(typeof initValue4 === "number") {
initValue4 = 1;
console.log(initValue4);
}
count = parseInt(initValue);
// 참조타입 배열
let list : number[] = [1,2,3,4,5]; // 요소들이 숫자형 타입이다.
let list2 : Array<number> = [1,2,3,4,5]; // 배열의 요소들이 숫자형 타입이다. // Array<number> 제네릭
// 하나의 사이즈의 요소를 가질수 있는 number의 타입만 가질수 있는 배열
// 고정의 사이즈와 각 요소의 타입을 정의하는 형태를 튜플 타입
let list3 : [string, number] = ["id",1];
list3[0].replace("i", "");
list3[1] // number
// void 반환값이 없는 함수
// const add = (a : number, b : number) : void => {
// return a + b;
// }
// const add = (a : number, b : number) : number => {
// return a + b;
// }
// function add2 () : number {
// return 1;
// }
// 추상 클래스 객체의 형태를 정의해서 사용
// interface 추상 클래스 선언 예약어
// I 대문자를 이름 앞에 붙여서 명시
interface IBlock {
id : number,
num : number
}
// object
let object : IBlock = {
id : 123,
num : 123,
}
// implements 추상 클래스를 상속 즉 형태를 상속받는다.
// extends 속성을 상속 받는다.
class Block implements IBlock {
id: number
num: number
constructor (_id : number) {
this.id = _id;
this.num = 1;
}
}
// const el : HTMLDivElement | null = document.querySelector(".item");
// 타입을 추론할때 내가 알려줄게 이 타입의 값이 들어있는 변수야
// (el as HTMLDivElement).onclick = (e : MouseEvent) => {
// }
// const add = (count : string) : number => {
// const add_count : number = 1;
// return count + add_count;
// }
console.log(message);
이렇게 Typescript 파일로 작성된 코드를 다음과 같은 명령어로 입력하면 자바스크립트 파일로 컴파일하게 됩니다. 그리고 동일한 코드로 변환된 index.js 파일이 생성되는 겁니다.
tsconfig.json
{
// compilerOptions 코드 변환시 사용하는 속성들
"compilerOptions": {
"target": "es6", // 출력할 js의 문법 대상
"module": "commonjs", // 사용하는 모듈 시스템,
"strict": true, // 엄격한 타입 검사
"outDir": "./dist", // 파일을 변환한 뒤에 어느 경로로 내보낼건지
"sourceMap": true // 디버깅 소스를 만들어서 어디서 에러가 발생했는지 .js.map 변환이후에 타입스크립트의 에러를 추적 할수 있게한다.
},
"include": ["src/**/*"] // 컴파일할 파일의 경로를 지정 경로 패턴 /** 모든 폴더 /* 모든 파일
}
현재 컴파일 속성들을 보면 include 속성을 src 폴더에 모든 경로, 모든 파일을 컴파일하도록 되어있습니다. 따라서 다음과 같은 명령어를 입력하면 컴파일된 파일들이 /dist 폴더에 내보내졌습니다.
$ npx tsc

컴파일된 파일들 중 예시로 컴파일된 index.js
// 원시타입
var message = "hello TypeScript";
var count = 123456;
var isActive = false;
var hash = "0xfeself"; // 진수는 숫자형 데이터가 맞다. 하지만 우리가 사용할대 많이 문자열로 사용한다.
var initValue = "123"; // 타입검사를 하지 않겠다 any 쓰지마라 이거 사용할거면 자바스크립트를 사용하게 좋다.
// any 타입검사를 할수 없는 경우가 생긴다.
// 모듈 시스템 라이브러리에서 타입의 모듈을 제공하지 않는 경우 진짜 불가피한경우 사용해라
var initValue2 = undefined;
var initValue3 = null;
var initValue4 = "123";
// any unknown 의 차이
// any는 무슨 값인지 아예 몰라. 완전 타입검사를 강력하게 풀었다.
// unknown 타입을 특정할수는 없는데 검사는 또 하고싶어 검증은 필요해
//
initValue = 1;
// unknown 값을 재할당할때 조건이 필요하다
// 조건문 이후에 사용을 해야한다.
if (typeof initValue4 === "number") {
initValue4 = 1;
console.log(initValue4);
}
count = parseInt(initValue);
// 참조타입 배열
var list = [1, 2, 3, 4, 5]; // 요소들이 숫자형 타입이다.
var list2 = [1, 2, 3, 4, 5]; // 배열의 요소들이 숫자형 타입이다. // Array<number> 제네릭
// 하나의 사이즈의 요소를 가질수 있는 number의 타입만 가질수 있는 배열
// 고정의 사이즈와 각 요소의 타입을 정의하는 형태를 튜플 타입
var list3 = ["id", 1];
list3[0].replace("i", "");
list3[1]; // number
// object
var object = {
id: 123,
num: 123,
};
// implements 추상 클래스를 상속 즉 형태를 상속받는다.
// extends 속성을 상속 받는다.
var Block = /** @class */ (function () {
function Block(_id) {
this.id = _id;
this.num = 1;
}
return Block;
}());
// const el : HTMLDivElement | null = document.querySelector(".item");
// 타입을 추론할때 내가 알려줄게 이 타입의 값이 들어있는 변수야
// (el as HTMLDivElement).onclick = (e : MouseEvent) => {
// }
// const add = (count : string) : number => {
// const add_count : number = 1;
// return count + add_count;
// }
console.log(message);
2-2. 타입스크립트 설정파일 tsconfig.json
tsconfig.json 이란?
tsc(타입스크립트 컴파일러)가 어떤 파일을 어떻게 컴파일할지 설정하는 파일
즉, 쉽게 말해 타입스크립트로 작성된 파일을 자바스크립트로 변환 시키는 컴파일 설정을 한꺼번에 정의하는 설정파일이라고 보시면 됩니다.
다음 코드를 실행하면 tsconfig.json 파일을 생성해줍니다.
$ tsc --init
이런 내용들이 나타나면서

이렇게 파일이 생성되어야 합니다.

이렇게 컴파일 옵션들이 있습니다. 자주 사용되는 속성들만 짚어보시죠
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "libReplacement": true, /* Enable lib replacement. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
먼저 "target" 속성입니다.
1. target
컴파일된 자바스크립트 코드가 어떤 버전의 문법으로 변환할지 사용되는 속성
말 그대로 ES5 문법, ES6 문법등 다양한 버전의 문법들이 있겠죠?
이렇게 지정하면 컴파일된 코드가 ES6 버전으로 변환된다는 겁니다.
"target": "es6"
2. module
어떤 모듈 시스템을 사용할지를 지정하는 옵션
쉽게 말하면 import/export 구문을 어떻게 변환해서 js로 만들지 정하는 옵션이라고 생각하시면 됩니다.
"module": "commonjs"
이렇게 지정할 수도 있습니다. 가장 보편적인 Node.js 에서 쓰이는 방식으로 예시를 두었습니다.
3. Strict
엄격한 타입 검사를 설정하는 옵션
말 그대로 엄격한 타입을 검사하는 옵션입니다. 예를 들면 null 이나 undefined를 명시적으로 처리해야하는 "strictNullChecks" 속성 등 다양한 속성이 있습니다.
4. outDir
컴파일된 파일을 어떤 폴더 경로에 저장할지 지정하는 옵션
5. sourceMap
디버깅 소스를 만들어서 어디서 에러가 발생했는지 .js.map 변환이후에 타입스크립트의 에러를 추적 할수 있게 해주는 옵션
6. include
컴파일할 파일의 경로를 지정하는 옵션
2-3.타입스크립트 빌드(트랜스파일)
## 설정파일을 읽고 패키지를 실행시켜서 파일을 컴파일한다. 즉 파일 변환이 일어난다 설정파일에 속성을 가지고
$ npx tsc
3. 타입스크립트와 객체지향
3-1. 객체지향의 개념
서로 다른 역할을 가진 객체들이 협력하며 데이터를 처리하고 문제를 해결하는 프로그래밍 설계 방식
3-2. 클래스와 인스턴스
클래스
클래스는 객체를 만들기 위한 틀이라고 보시면됩니다.
인스턴스
인스턴스는 클래스를 통해 만들어진 실제 객체를 뜻합니다.
// 클래스 정의
class Person {
name: string;
constructor(name) {
this.name = name;
}
greet() {
console.log(`안녕하세요, 저는 ${this.name}입니다.`);
}
}
// 새로운 인스턴스 생성
const p1 = new Person("짱구");
const p2 = new Person("철수");
p1.greet();
p2.greet();
3-3. 상속과 캡슐화
상속
부모 클래스로부터 속성과 메서드를 자식 클래스가 물려 받는것을 뜻합니다.
캡슐화
데이터를 외부에서 접근하지 못하도록 보호하고, 필요한 경우 메서드를 통해 접근을 제어하는 개념
자바에서 public, private, protected 같은 키워드를 사용하는 것처럼 외부에서 접근하는 데이터를 막는것을 말합니다.
3-4. 추상화 && 다형성
추상화
복잡한 구현 숨기고 핵심만 표현한 것
다형성
같은 메서드 호출이 다른 동작 수행
결론
타입스크립트는 자바스크립트에 정적 타입을 추가해 코드 안정성과 가독성을 높여주고, 객체지향 프로그래밍과 최신 문법을 지원하여 대규모 프로젝트에 적합합니다. 컴파일 과정을 거쳐 다양한 환경에서 호환 가능한 자바스크립트로 변환됩니다.
'Typescript 기록' 카테고리의 다른 글
타입스크립트 인터페이스(Interface) (1) | 2025.06.17 |
---|---|
타입스크립트 타입 어서션, 타입 엘리어스, 타입 클래스 수정자, 전략패턴 (0) | 2025.06.16 |
타입스크립트 자료형 (1) | 2025.06.16 |