Skip to main content

TypeScript in Visual Studio Code

Visual Studio Code (VS Code) has become the go-to editor for TypeScript development, and for good reason. Microsoft develops both TypeScript and VS Code, resulting in first-class integration between the two. In this guide, you'll learn how to set up, configure, and optimize VS Code for TypeScript development.

Why VS Code for TypeScript?

VS Code provides an exceptional TypeScript development experience with features like:

  • IntelliSense with type information
  • Built-in TypeScript language service
  • Quick fixes and refactoring tools
  • Integrated debugging support
  • Excellent extension ecosystem

Setting Up VS Code for TypeScript

Step 1: Install VS Code

First, download and install Visual Studio Code from code.visualstudio.com.

Step 2: Install Node.js and TypeScript

TypeScript requires Node.js to run. Once you have Node.js installed, you can install TypeScript globally:

bash
npm install -g typescript

Step 3: Create a TypeScript Project

Create a new directory for your project and initialize it with TypeScript:

bash
mkdir ts-project
cd ts-project
npm init -y
npm install typescript --save-dev
npx tsc --init

The last command creates a tsconfig.json file, which configures TypeScript's behavior in your project.

Essential VS Code Features for TypeScript

IntelliSense

VS Code's IntelliSense provides intelligent code completions based on type information. As you type, you'll get suggestions for variables, functions, and methods appropriate for the context.

For example, when working with an object that has specific properties:

typescript
interface User {
name: string;
age: number;
isActive: boolean;
}

const user: User = {
name: "John",
age: 30,
isActive: true
};

// When you type 'user.' VS Code will suggest name, age, and isActive
user. // IntelliSense will show available properties

Type Checking

VS Code displays type errors in real time. Hover over the red squiggly underlines to see detailed error messages:

typescript
// This will show an error in VS Code
const name: string = 42; // Type 'number' is not assignable to type 'string'

Code Navigation

VS Code makes navigating TypeScript code easy:

  • Go to Definition: Right-click on a symbol and select "Go to Definition" or press F12
  • Find all References: Right-click and select "Find all References" or press Shift+F12
  • Peek Definition: Right-click and select "Peek Definition" or press Alt+F12

Refactoring Tools

VS Code provides several refactoring options for TypeScript:

  • Rename Symbol: Right-click and select "Rename Symbol" or press F2
  • Extract Method/Variable: Select code, right-click and choose from refactoring options
  • Organize Imports: Right-click and select "Organize Imports" or use the keyboard shortcut

Must-Have Extensions for TypeScript Development

1. ESLint

ESLint helps maintain code quality by enforcing consistent style and catching potential errors:

bash
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

Create a .eslintrc.js file:

javascript
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
// Your custom rules
}
};

Install the ESLint extension in VS Code for real-time linting.

2. Prettier

Prettier automatically formats your code for consistent style:

bash
npm install --save-dev prettier

Create a .prettierrc file:

json
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}

Install the Prettier extension in VS Code and enable "Format on Save" in settings.

3. Path Intellisense

This extension autocompletes filenames as you import them:

typescript
import { Component } from './com' // Will suggest 'components'

4. GitLens

GitLens enhances Git integration in VS Code, showing line-by-line Git history inline.

VS Code Configurations for TypeScript

Custom settings.json

Here's a recommended settings.json configuration for TypeScript development:

json
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"typescript.updateImportsOnFileMove.enabled": "always",
"typescript.preferences.importModuleSpecifier": "relative",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.tabSize": 2,
"typescript.suggest.autoImports": true
}

Creating Tasks for TypeScript

VS Code tasks can automate TypeScript operations. Create a .vscode/tasks.json file:

json
{
"version": "2.0.0",
"tasks": [
{
"label": "TypeScript Compile",
"type": "shell",
"command": "npx tsc",
"problemMatcher": ["$tsc"],
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "TypeScript Watch",
"type": "shell",
"command": "npx tsc --watch",
"problemMatcher": ["$tsc-watch"],
"group": "build",
"isBackground": true
}
]
}

Now you can run these tasks from the Terminal menu or by pressing Ctrl+Shift+B.

Debugging TypeScript in VS Code

VS Code has excellent support for debugging TypeScript applications. Let's set up a basic debugging configuration:

Step 1: Install ts-node

bash
npm install --save-dev ts-node

Step 2: Create a Launch Configuration

Create a .vscode/launch.json file:

json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Current TS File",
"type": "node",
"request": "launch",
"runtimeArgs": ["-r", "ts-node/register"],
"args": ["${file}"],
"cwd": "${workspaceFolder}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "Debug Program",
"type": "node",
"request": "launch",
"runtimeArgs": ["-r", "ts-node/register"],
"args": ["${workspaceFolder}/src/index.ts"],
"cwd": "${workspaceFolder}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
}
]
}

Step 3: Use Breakpoints

Now you can set breakpoints in your TypeScript code by clicking in the gutter (left margin of the editor). Press F5 to start debugging.

typescript
// Example with breakpoint
function calculateTotal(prices: number[]): number {
let total = 0;

for (const price of prices) {
// Set breakpoint on the next line
total += price;
}

return total;
}

const result = calculateTotal([10, 20, 30, 40]);
console.log(`Total: ${result}`); // Output: Total: 100

During debugging, you can:

  • Hover over variables to see their values
  • Use the Debug console to evaluate expressions
  • Step through code line by line with the debug controls

Productivity Tips

Keyboard Shortcuts

Master these shortcuts to accelerate your TypeScript development:

  • F12: Go to definition
  • Alt+F12: Peek definition
  • Shift+F12: Find all references
  • F2: Rename symbol
  • Ctrl+Space: Trigger suggestions
  • Ctrl+.: Show quick fixes
  • Ctrl+Shift+B: Run build task

Code Snippets

Create custom TypeScript snippets via File > Preferences > User Snippets > TypeScript:

json
{
"TypeScript Class": {
"prefix": "tsclass",
"body": [
"export class ${1:ClassName} {",
" constructor() {",
" $0",
" }",
"}"
],
"description": "TypeScript class definition"
},
"TypeScript Interface": {
"prefix": "tsinterface",
"body": [
"export interface ${1:InterfaceName} {",
" $0",
"}"
],
"description": "TypeScript interface definition"
}
}

Now you can type tsclass or tsinterface and press Tab to insert these snippets.

Real-World Project Structure in VS Code

Here's how you might structure a typical TypeScript project in VS Code:

project-root/
├── .vscode/
│ ├── launch.json # Debug configurations
│ └── tasks.json # Build tasks
├── src/
│ ├── index.ts # Entry point
│ ├── models/ # Type definitions
│ ├── services/ # Business logic
│ └── utils/ # Helper functions
├── tests/ # Test files
├── .eslintrc.js # ESLint config
├── .prettierrc # Prettier config
├── package.json # Dependencies
└── tsconfig.json # TypeScript config

Real-World Example: ToDo Application

Let's see how VS Code features help in developing a small ToDo application:

src/models/todo.ts:

typescript
export interface Todo {
id: number;
title: string;
completed: boolean;
}

src/services/todoService.ts:

typescript
import { Todo } from '../models/todo';

export class TodoService {
private todos: Todo[] = [];

addTodo(title: string): Todo {
const newTodo: Todo = {
id: Date.now(),
title,
completed: false
};

this.todos.push(newTodo);
return newTodo;
}

toggleTodo(id: number): Todo | undefined {
const todo = this.todos.find(t => t.id === id);

if (todo) {
todo.completed = !todo.completed;
}

return todo;
}

getAllTodos(): Todo[] {
return [...this.todos];
}
}

src/index.ts:

typescript
import { TodoService } from './services/todoService';

const todoService = new TodoService();

// Add some todos
todoService.addTodo("Learn TypeScript");
todoService.addTodo("Set up VS Code");
const codeTodo = todoService.addTodo("Write clean code");

// Complete a todo
todoService.toggleTodo(codeTodo.id);

// Show all todos
console.log("All Todos:");
todoService.getAllTodos().forEach(todo => {
const status = todo.completed ? "✓" : "○";
console.log(`${status} ${todo.title}`);
});

// Output:
// All Todos:
// ○ Learn TypeScript
// ○ Set up VS Code
// ✓ Write clean code

As you develop this application, VS Code will:

  1. Validate your types across files
  2. Provide autocompletion for the Todo properties
  3. Help you navigate between files with Go to Definition
  4. Show errors if you try to access non-existent properties

Summary

Visual Studio Code provides an exceptional environment for TypeScript development with its built-in features and powerful extension ecosystem. In this guide, we've covered:

  • Setting up VS Code for TypeScript development
  • Essential VS Code features for TypeScript
  • Must-have extensions for productivity
  • VS Code configurations and settings
  • Debugging TypeScript applications
  • Productivity tips and keyboard shortcuts
  • Real-world project structure and examples

By mastering VS Code for TypeScript development, you'll significantly improve your coding efficiency and quality. The combination of static type checking, intelligent code completion, and automated tools helps catch errors early and makes your development workflow smoother.

Additional Resources

Practice Exercises

  1. Set up a new TypeScript project in VS Code with ESLint and Prettier.
  2. Create a debug configuration that lets you debug a specific file.
  3. Create custom snippets for TypeScript patterns you use frequently.
  4. Extend the ToDo application by adding methods to delete todos and filter by completed status.
  5. Configure a VS Code task that compiles TypeScript and runs your application.

Happy coding with TypeScript and VS Code!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)