jsguides

Getting Started with TypeScript: Setup and First Project

TypeScript has become an essential skill for modern JavaScript development. Whether you are building a small frontend project or a large-scale enterprise application, TypeScript helps you write more reliable, maintainable code. Getting started with TypeScript is straightforward once you understand the core concepts of its type system and how the compiler fits into your workflow.

This guide walks through what TypeScript is, why it has become so popular, and how to set up your first TypeScript project. By the end, you will have a working TypeScript environment and understand the core concepts that will guide you through the rest of this series.

What is TypeScript?

TypeScript is a strongly typed programming language that builds on JavaScript. It was developed by Microsoft and released in 2012, designed to address some of JavaScript’s shortcomings, particularly around type safety and large-scale application development.

JavaScript is dynamically typed, meaning variable types are determined at runtime. This flexibility is powerful but can lead to unexpected bugs that only surface in production. TypeScript adds a type system on top of JavaScript, catching errors during development rather than at runtime.

// JavaScript - types are determined at runtime
function greet(name) {
  return "Hello, " + name.toUpperCase();
}

// TypeScript - types are checked during development
function greet(name: string): string {
  return "Hello, " + name.toUpperCase();
}

In the TypeScript version, the : string annotations tell the compiler that name should be a string and the function returns a string. If you try to pass a number or object, TypeScript will show an error in your editor before you even run the code.

Why use TypeScript?

TypeScript offers several compelling benefits:

  • Error Prevention: Catch bugs early in development with compile-time type checking
  • Better IDE Support: Enjoy improved autocomplete, refactoring, and navigation
  • Self-Documenting Code: Types serve as inline documentation
  • Safer Refactoring: Change code with confidence knowing TypeScript will catch breaking changes
  • Modern JavaScript: Access the latest JavaScript features with cross-browser compatibility

Installing TypeScript

Before you can start writing TypeScript, you need to install it. The easiest way is through npm (Node Package Manager), which comes with Node.js.

Installing Node.js

If you do not have Node.js installed, download it from the official website or use a version manager like nvm:

# Check if Node.js is installed
node --version

# Check if npm is installed
npm --version

If both commands return version numbers, you are ready to proceed. Version managers like nvm let you switch between Node.js versions per project, which is useful when working on multiple TypeScript codebases with different requirements.

Installing TypeScript globally

Install the TypeScript compiler (tsc) globally so you can use it from any directory:

npm install -g typescript

# Verify installation
tsc --version

Installing TypeScript locally

For projects, it is often better to install TypeScript as a development dependency. This approach keeps the TypeScript version pinned in your package.json and ensures every developer on the team uses the same compiler:

mkdir my-typescript-project
cd my-typescript-project
npm init -y
npm install --save-dev typescript

Your first TypeScript file

Now that TypeScript is installed, create your first TypeScript program. Start with a simple function that demonstrates how type annotations catch mistakes before runtime.

Creating the project

Create a new file called index.ts in your project directory:

// index.ts
function add(a: number, b: number): number {
  return a + b;
}

const result = add(5, 10);
console.log("The sum is:", result);

This function accepts two numbers and returns their sum. The type annotations on the parameters and return value tell TypeScript exactly what the function expects, which means the compiler will flag any attempt to pass a string or other type.

Compiling TypeScript

Compile your TypeScript file to JavaScript using the TypeScript compiler:

tsc index.ts

This creates an index.js file with the compiled JavaScript. The compiler strips away all TypeScript-specific syntax and produces clean ES5 or later JavaScript, depending on your configuration:

// index.js (compiled from TypeScript)
function add(a, b) {
  return a + b;
}
var result = add(5, 10);
console.log("The sum is:", result);

Running the code

Execute the compiled JavaScript with Node.js to verify the output:

node index.js
# Output: The sum is: 15

Basic types in TypeScript

TypeScript provides several basic types that form the foundation of the type system. Understanding these primitives is the first step toward writing type-safe code.

Primitive types

TypeScript supports three primitive types that map directly to JavaScript’s runtime types:

// String
let message: string = "Hello, TypeScript";

// Number (all numbers, including floats)
let count: number = 42;
let price: number = 19.99;

// Boolean
let isActive: boolean = true;
let isComplete: boolean = false;

Type inference

TypeScript can automatically infer types when you provide an initial value. This means you do not always need to write explicit annotations — but adding them improves readability and serves as documentation for anyone reading your code later:

// TypeScript infers the type from the initial value
let name = "Alice";     // inferred as string
let age = 25;           // inferred as number
let isStudent = false; // inferred as boolean

Arrays

Define arrays using type[] or Array<type> syntax. Both forms are equivalent — pick whichever reads more naturally in context:

let numbers: number[] = [1, 2, 3, 4, 5];
let names: Array<string> = ["Alice", "Bob"];
let mixed: (string | number)[] = [1, "two", 3];

Objects

Define object types with explicit property types to document the shape of data structures:

let person: {
  name: string;
  age: number;
  email: string;
} = {
  name: "Alice",
  age: 25,
  email: "alice@example.com"
};

Any and unknown

When you are unsure about a type, TypeScript provides two escape hatches. Use unknown when you need to accept any value but will narrow it before using it — this is safer than any, which disables type checking completely:

// any - disables type checking (avoid when possible)
let anything: any = "hello";
anything = 42;
anything = true;

// unknown - type-safe any
let something: unknown = "hello";
// You must narrow the type before using it
if (typeof something === "string") {
  console.log(something.toUpperCase());
}

The TypeScript configuration file

The tsconfig.json file controls how TypeScript compiles your code. It is the central place to configure target output, strictness, module format, and input/output directories.

Creating a config file

Generate a default configuration with a single command:

tsc --init

This creates a tsconfig.json with sensible defaults that work for most projects:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

Key compiler options

Understanding these options will help you configure TypeScript for your needs:

OptionDescription
targetJavaScript version to compile to (ES5, ES6, ES2020, etc.)
strictEnable all strict type checking options
moduleModule system to use (CommonJS, ESNext, etc.)
outDirOutput directory for compiled files
rootDirRoot directory of input files
noImplicitAnyError on expressions with implied any type

Watching for changes

Instead of running tsc manually each time, use watch mode to recompile automatically when files change:

tsc --watch

Working with an IDE

TypeScript truly shines when paired with a good IDE. Visual Studio Code, developed by Microsoft, provides excellent TypeScript support out of the box.

Visual Studio Code

VS Code includes TypeScript support and provides:

  • Real-time type checking and error highlighting
  • Intelligent autocomplete
  • Go-to-definition and find references
  • In-line documentation on hover
  • Refactoring tools

If you are using another editor, most modern editors have TypeScript extensions available.

Common TypeScript errors

As you start writing TypeScript, you will encounter some common errors. Understanding them helps you fix them quickly and teaches you how the type system thinks.

Type mismatch

// Error: Type '"5"' is not assignable to type 'number'
let num: number = "5";

Fix: Use the correct type or convert the value with Number("5") or parseInt.

Property does not exist

let user = { name: "Alice" };
// Error: Property 'age' does not exist on type '{ name: string; }'
console.log(user.age);

Fix: Add the property to the object definition or use optional properties with ? syntax like age?: number.

Implicit any

function greet(name) {  // Parameter 'name' implicitly has an 'any' type
  return "Hello, " + name;
}

Fix: Add a type annotation or enable noImplicitAny in your config to catch these at compile time.

Where to go from here

You now have a solid foundation in TypeScript. Here is what to explore next:

  • Types and Interfaces: Define custom types for your data structures
  • Functions: Learn about function types, overloads, and generic functions
  • Classes: Understand object-oriented programming in TypeScript
  • Modules: Organize code across multiple files

The next tutorial in this series covers types and interfaces in detail, building on what you have learned here.

Let the compiler teach you

Many beginners think of TypeScript as a gate that stops code from running. A better mental model is that it is a conversation partner that points out assumptions before they escape into the browser. When the compiler complains, read the message as a clue about the data shape you actually have. That habit makes your code clearer and helps you choose better names, better boundaries, and better function signatures.

Build the habit gradually

The first benefit of TypeScript is usually not perfect type coverage — it is the early feedback loop. Start with a small project, turn on the compiler, and fix the errors that matter most. That approach keeps the learning curve manageable and helps you see which kinds of bugs the type system can catch for you. Once that feels natural, you can add stricter settings and more precise types without turning the setup into a chore.

Conclusion

TypeScript transforms JavaScript development by adding powerful type checking that catches errors before they reach production. You have now learned what TypeScript is, why it matters, and how to set up your development environment. You also explored basic types and the TypeScript configuration file.

The investment in learning TypeScript pays dividends in code quality, developer productivity, and maintainability. As you continue through this series, you will discover more advanced features that make TypeScript an indispensable tool for modern web development.

See Also