Get Started with TypeScript | Install, tsconfig, and Basic Syntax
이 글의 핵심
A practical guide to getting started with TypeScript: installation, configuration, basic types and functions, VS Code workflow, and a hands-on calculator example.
Introduction
What is TypeScript?
TypeScript is a superset of JavaScript developed by Microsoft—you write types that erase when you compile to JavaScript, so browsers still run plain JS.
TypeScript = JavaScript + a type system
Key features:
- ✅ Static typing: type checking at compile time
- ✅ Autocomplete: stronger IDE support
- ✅ Refactoring: safer code changes
- ✅ Modern syntax: ES6+ support
- ✅ Compatibility: compiles to JavaScript
1. TypeScript vs JavaScript
Comparison
| Feature | JavaScript | TypeScript |
|---|---|---|
| Types | Dynamic | Static |
| Compile | Not required | Required (→ JS) |
| Error detection | Runtime | Compile time |
| IDE support | Basic | Strong |
| Learning curve | Lower | Medium |
Example
This example shows how type safety differs between JavaScript and TypeScript:
// JavaScript: dynamic types
function add(a, b) {
// a and b have no explicit types
// they can be anything
return a + b;
}
console.log(add(10, 20)); // 30 (numeric addition)
console.log(add("10", "20")); // "1020" (string concatenation)
// Unintended result!
// Runs without a runtime error, but it is a logical bug
// No type checking before execution
console.log(add(10, "20")); // "1020" (number + string)
console.log(add(null, 10)); // 10 (null coerces)
console.log(add(undefined, 10)); // NaN (undefined becomes NaN)
// Unexpected behaviors
// TypeScript: static types
function add(a: number, b: number): number {
// a: number — a must be a number
// b: number — b must be a number
// : number — return type is number
return a + b;
}
console.log(add(10, 20)); // ✅ 30 (OK)
// Errors caught at compile time
console.log(add("10", "20")); // ❌ compile error!
// Error message:
// Argument of type 'string' is not assignable to parameter of type 'number'
//
// Bugs found before running the code (safer)
// Other wrong types are errors too
// console.log(add(10, "20")); // ❌ error
// console.log(add(null, 10)); // ❌ error
// console.log(add(undefined, 10)); // ❌ error
Benefits of TypeScript:
- Compile-time errors: catch bugs before execution
- Autocomplete: the IDE uses types for accurate suggestions
- Refactoring: changing a type surfaces all usages
- Documentation: types document intent (fewer comments needed)
Real-world example:
// API response shape
interface User {
id: number;
name: string;
email: string;
}
function getUser(id: number): User {
// Return type is guaranteed to be User
return {
id: id,
name: "Alice",
email: "[email protected]"
};
}
const user = getUser(1);
console.log(user.name); // IDE autocompletes name
// console.log(user.age); // ❌ error: User has no age
2. Installation and setup
Install Node.js
TypeScript runs in a Node.js environment.
- Download from the official Node.js site
- Verify installation:
node --version
npm --version
Install TypeScript
# Global install
npm install -g typescript
# Verify version
tsc --version
Initialize a project
# Create project folder
mkdir my-typescript-project
cd my-typescript-project
# Create package.json
npm init -y
# Install TypeScript locally
npm install --save-dev typescript
# Create tsconfig.json
npx tsc --init
3. tsconfig.json
Basic configuration
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Common options
| Option | Description |
|---|---|
target | JavaScript version to emit |
module | Module system (commonjs, es6, etc.) |
outDir | Output folder for compiled files |
rootDir | Root folder for source files |
strict | Enable strict type checking |
esModuleInterop | Better CommonJS / ES module interop |
4. Your first TypeScript program
Project layout
my-typescript-project/
├── src/
│ └── index.ts
├── dist/
├── package.json
└── tsconfig.json
index.ts
// src/index.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
const userName: string = "Alice";
console.log(greet(userName));
// Type error example
// console.log(greet(123)); // ❌ error: number is not assignable to string
Compile and run
# TypeScript → JavaScript
npx tsc
# Run compiled output
node dist/index.js
Output:
Hello, Alice!
5. Basic types
Primitive types
// Numbers
let age: number = 25;
let price: number = 19.99;
// Strings
let name: string = "Alice";
let message: string = `Hello, ${name}!`;
// Booleans
let isActive: boolean = true;
let isCompleted: boolean = false;
// null and undefined
let empty: null = null;
let notDefined: undefined = undefined;
Arrays
// Style 1: Type[]
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Carol"];
// Style 2: Array<Type>
let scores: Array<number> = [90, 85, 95];
// Nested arrays
let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6]
];
Tuples
// Tuple: fixed length and element types
let person: [string, number] = ["Alice", 25];
console.log(person[0]); // Alice
console.log(person[1]); // 25
// person[2] = "NYC"; // ❌ error: index out of defined tuple length
any and unknown
// any: allow anything (disables type checking for this value)
let anything: any = 10;
anything = "text";
anything = true;
// unknown: type-safe alternative to any
let value: unknown = 10;
// console.log(value.toFixed(2)); // ❌ error
// Narrow before use
if (typeof value === "number") {
console.log(value.toFixed(2)); // ✅ OK
}
6. Function types
Basic functions
// Parameters and return type
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const subtract = (a: number, b: number): number => {
return a - b;
};
// No return value
function log(message: string): void {
console.log(message);
}
Optional parameters
function greet(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Alice", "Hi there")); // Hi there, Alice!
Default parameters
function createUser(name: string, age: number = 20): object {
return { name, age };
}
console.log(createUser("Alice")); // { name: 'Alice', age: 20 }
console.log(createUser("Bob", 25)); // { name: 'Bob', age: 25 }
7. Development environment
VS Code extensions
- TypeScript Importer: automatic imports
- ESLint: code quality
- Prettier: formatting
- Path Intellisense: path autocomplete
ts-node
Run TypeScript without a separate compile step:
npm install --save-dev ts-node
# Run
npx ts-node src/index.ts
nodemon
Restart on file changes:
npm install --save-dev nodemon
// package.json
{
"scripts": {
"dev": "nodemon --exec ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}
npm run dev
8. Hands-on example
Simple calculator
// src/calculator.ts
type Operation = 'add' | 'subtract' | 'multiply' | 'divide';
function calculate(a: number, b: number, op: Operation): number {
switch (op) {
case 'add':
return a + b;
case 'subtract':
return a - b;
case 'multiply':
return a * b;
case 'divide':
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
default:
throw new Error(`Unknown operation: ${op}`);
}
}
// Usage
console.log(calculate(10, 5, 'add')); // 15
console.log(calculate(10, 5, 'subtract')); // 5
console.log(calculate(10, 5, 'multiply')); // 50
console.log(calculate(10, 5, 'divide')); // 2
Summary
Takeaways
- TypeScript: JavaScript plus types
- Install:
npm install -g typescript - Config:
tsconfig.json - Compile:
tsc - Basics:
number,string,boolean, arrays, tuples
Next steps
Compare with other languages
- JavaScript fundamentals | A complete intro for web development
Related posts
- Python environment setup | Install and start on Windows and Mac
- C++ development environment guide | OS, tools, and setup
- Top 15 beginner C++ mistakes | From compile errors to runtime crashes
- HTML & CSS fundamentals | First steps in web development
- Java from scratch | JDK install to Hello World