Getting Started with TypeScript: A comprehensive introduction

Learn the basics of TypeScript and start building powerful JavaScript apps today

·

14 min read

Introduction to TypeScript

TypeScript has rapidly emerged as one of the most popular and impactful programming languages in web development. With its powerful typing system and modern language features, TypeScript helps developers build large-scale JavaScript applications with confidence.

In this comprehensive guide, we will look at what makes TypeScript so important and how it builds on JavaScript to provide game-changing advantages. Whether you are new to TypeScript or want to go deeper into its capabilities, this guide will walk you through everything from the basics and history to advanced concepts and real-world usage.

By the end, you will understand why TypeScript usage has skyrocketed and have the foundation to start leveraging it in your own projects. So let's dive in and uncover what makes TypeScript so essential for modern JavaScript development!

Why TypeScript Matters: Enabling Scalable Web Apps

Before we look at TypeScript's origins and features, it's important to understand the core problem it aims to solve.

JavaScript is an flexible dynamic language, but that flexibility comes at a cost. Lack of static typing and tooling support makes building and maintaining large web apps difficult. Bugs and runtime errors easily creep in as codebases grow.

What Exactly is TypeScript?

TypeScript is a typed superset of JavaScript created by Microsoft that compiles down to plain JavaScript. Here are some key things to know about TypeScript:

  • Adds optional static typing to standard JavaScript syntax

  • Compiles to vanilla JavaScript that runs anywhere JavaScript runs

  • Created and maintained by Microsoft but open source and community-driven

  • Provides modern language features like classes, modules, generics and more

  • Enables intelligent tooling and editor support like autocomplete, refactoring and checking

In a nutshell, TypeScript gives you the best of both worlds - the flexibility and familiarity of JavaScript with the safety and tooling of a typed language like C# or Java.

As web apps become ever more complex, TypeScript serves as the scaffolding to build robust frontend architecture. It supercharges developer productivity with great editor support while preventing entire classes of bugs.

Now that we've seen the prime motivation for TypeScript, let's look at how it came into being and achieved mainstream popularity.

History and Development of TypeScript

TypeScript origins trace back to the early 2000s at Microsoft when the initial design work for a statically typed JavaScript was started. After several years of experimentation and refinement, TypeScript was publicly released in 2012. Let's dive into some key milestones:

Early Research at Microsoft

The seeds for TypeScript were planted when Microsoft program managers Anders Hejlsberg and Steve Lucco began collaborating on ideas for adding static typing to ECMAScript 4, which later evolved into ECMAScript 5 and the modern JavaScript we know today.

Their work did not materialize immediately, but helped establish core principles like keeping the addition of types optional. The research ultimately led to the beginnings of TypeScript after many years of incubation.

Key Milestones

Some notable milestones in TypeScript's meteoric growth after its 1.0 release include:

  • 2014 - TypeScript support added to Visual Studio Code and Angular 2 announcement

  • 2015 - TypeScript definitions for React released and TS tooling improves

  • 2016 - Angular 2 in TypeScript released. TypeScript 2.0 adds significant features

  • 2017 - 3x growth in TypeScript usage. Strict mode and version 2.4 released

  • 2018 - TypeScript 3.0 adds project references and React announces TS support

  • 2019 - 3.5 delivers faster builds and more types. Over 50% JS devs use TS

  • 2020 - Deno 1.0 launches supporting TypeScript. TS 4.0 ships

  • 2021 - Next.js 12 adds full TypeScript support. Vite 2.0 released.

This steady stream of advancement helped cement TypeScript's dominance for scalable web development. Next let's dig into the details of TypeScript's typing system and main features.

TypeScript's Typing System and Syntax

TypeScript's core typing system is what sets it apart from vanilla JavaScript. Let's understand how it works along with main syntax features:

Getting Started with TypeScript

Ready to start using TypeScript? Here is how to set it up:

Install TypeScript

npm install -g typescript

This provides the tsc command to compile .ts files to .js.

Configure a Project

Add a tsconfig.json file to specify root files and compiler options:

 code{
  "compilerOptions": { 
    "target": "es5",
    "module": "commonjs" 
  }
}

Convert a .js File to .ts

Just rename a file from .js to .ts and add types!

Compile to JavaScript

tsc app.ts

This will output app.js that can run in Node. That's it - you're ready to build with TypeScript!

Core TypeScript Types

TypeScript provides type annotations that you can add to variable declarations, function parameters, return values etc:

const username: string = "hello";

function greet(name: string): string {
  return `Hello ${name}`;
}

Here are the main types you'll use:

  • string - Text values like "Hi"

  • number - Numeric values like 12

  • boolean - True/false values like true

  • any - Allow any value, useful for mixed data

  • void - Used for return type when no value returned

  • never - Represents values that should never occur

  • object - Any non-primitive value like arrays and classes

  • Array<type> - Array of elements like string[]

  • enum - Named constant values like {Active, Inactive}

  • interface - Contract for how objects should be shaped

Plus you can create custom types, unions, literals and more.

Optional Static Typing

TypeScript introduces syntax for applying types like number, string and boolean to variables, parameters and functions:

let price: number = 5; 

function sum(a: number, b: number) {
  return a + b;
}

The compiler validates values that match their annotated types and alerts any mismatches. Adding types is optional - existing JavaScript code is valid TypeScript.

Type Inference

TypeScript can automatically infer types in many cases so explicit annotations are optional:

let price = 5; // inferred as number 

function sum(a, b) {
  return a + b; // a and b inferred as numbers
}

This avoids verbosity where types are obvious while retaining type safety.

Interfaces

Interfaces declare the "shape" that values should have:

interface User {
  name: string;
  id: number;
}

function printUser(user: User) {
  console.log(user.name); 
}

Any object that matches the interface can be passed to printUser.

Helpful features:

  • Optional properties with ?

  • Readonly properties with readonly

  • Extending interfaces

  • Implementing interfaces in classes

Interfaces are a powerful way to define contracts in your code.

interface Order {
  id: number;
  title: string;
  price: number;
}

function printOrder(order: Order) {
  // ...
}

Interfaces help organize code into logical chunks and set expectations between different components.

Classes

TypeScript provides traditional object-oriented classes with inheritance, constructors and member methods:

class Order {

  constructor(public id: number, public title: string, public price: number) {}

  printOrder() {
    console.log(this.id, this.title, this.price);
  }

}

Classes serve as blueprints for creating objects with reusable logic and data structures.

TypeScript makes working with classes a joy

class User {

  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet() { 
    console.log(`Hello ${this.name}!`)
  }

}

const user = new User("John");
user.greet();

Key features include:

  • Fields, constructors, and methods

  • Inheritance with extends

  • Access modifiers like public and private

  • Abstract classes that can't be instantiated directly

  • Shorthand initialization with access modifiers

OOP in TypeScript will feel familiar if you've used languages like Java or C#.

Generics

Generics allow creating reusable components that maintain type information:

function echo<T>(value: T) : T {
  return value; 
}

echo<string>("Hello");
echo<number>(5);

Here the echo function works safely with any type while preventing errors.

Modules

TypeScript uses ES6 import/export syntax for modular architecture:

// Logger.ts
export class Logger {
  // ...
}

// App.ts
import { Logger } from './Logger';

Namespaces are also supported for internal module organization. Modules improve structural integrity as apps scale.

This covers the major aspects of TypeScript's type system and syntax. Static types form the foundation for TypeScript's powerful tooling and error-checking capabilities.

TypeScript Compiler and Configuration

The TypeScript compiler (tsc) transpile source .ts files into regular .js files that can run anywhere JavaScript is supported:

The full compilation pipeline includes:

  • Type-checking valid code

  • Removing type annotations

  • Transpiling ES6+ features to ES5

  • Inlining referenced modules

  • Minification and bundling

The compiler accepts configurations like tsconfig.json for settings like strict mode, lib support, and module system.

Understanding the compile process helps leverage TypeScript most effectively across different environments.

Configuring a tsconfig.json

The tsconfig.json file controls important compiler options:

{
  "compilerOptions": {

    "target": "ES2015", 
    "module": "commonjs",

    "strict": true,
    "noImplicitAny": true

  }
}

Key options:

  • target - JS version to compile to

  • module - Module system like CommonJS or ES Modules

  • strict - Enable all strict checking

  • noImplicitAny - Prevent implicitly any types

There are many more useful configuration flags.

Benefits of Using TypeScript

Let's highlight some of the major benefits provided by TypeScript:

Why Use TypeScript Over JavaScript?

TypeScript offers some huge benefits over raw JavaScript:

Catch Errors Early

TypeScript's static analysis identifies problems in your code before you even run it:

// Type mismatch prevents runtime bug
const message: string = 123;

Bugs that would normally crash your app surfaced right away.

Readable Code

Types document how code is supposed to be used, acting like embedded documentation:

// Parameter types make usage clear
function greeting(name: string) {
  console.log(`Hello ${name}!`) 
}

Self-documented code helps understand complex systems faster.

Scalable Apps

TypeScript allows building massive apps that stay maintainable over time:

// NestJS example
@Controller()
class UsersController {

  @Get()
  findAll(@Query() query: UserQueryDto) {
    // ...
  }

}

Type safety prevents "code rot" as apps grow.

Type Safety

TypeScript's static analysis prevents entire classes of runtime errors like:

// Mismatched types
let price = '5'; 
let total = price + 5; // Error

Values are guaranteed to match expected types - a major source of bugs gone.

Code Understandability

Types document how code is meant to be used. They serve as embedded documentation readable during development:

// Function comment unnecessary due to types
function sum(num1: number, num2: number) {
  return num1 + num2;
}

Self-documented code improves maintainability as complexity increases.

Rich Tooling

One of the best parts of TypeScript is the incredible tooling support in code editors.

For example, VS Code provides:

  • Accurate autocomplete

  • Inline documentation

  • Robust refactoring

  • Useful error highlighting

The typing system enables building the best editing experience possible.

Interoperability

TypeScript integrates seamlessly with all existing JavaScript code and runtimes like Node.js. Types can be added to any JavaScript library to enable typed usage.

This flexibility and interoperability with billions of lines of existing JS code helped TypeScript's popularity.

These factors make TypeScript a uniquely productive choice for end-to-end web application development.

TypeScript in Action

Let's go through some real-world TypeScript examples to see how everything comes together:

Classes and Interfaces

Here a User class implements the UserSchema interface:

interface UserSchema {
  id: number;
  firstName: string;
  lastName: string;
}

class User implements UserSchema {
  id: number;
  firstName: string;
  lastName: string;

  constructor(id: number, firstName: string, lastName: string) {
    this.id = id;
    this.firstName = firstName; 
    this.lastName = lastName;
  }
}

const user = new User(1, "John", "Doe");

The class guarantees objects adhere to the interface shape.

Typing React Components

Components can be typed for robust React applications:

interface Props {
  message: string;
}

function Hello(props: Props) {
  return <div>{props.message}</div>;
}

// Invalid prop will error
<Hello message={5} />

Notice how types prevent bugs in JSX usage.

Generic Functions

Here a generic makeRequest function handles different request types:

interface Options {
  url: string;
  method: string;
  data?: any;
}

function makeRequest<T>(options: Options): Promise<T> {
  // ... 
}

const data = await makeRequest<string>({ url: "/", method: "GET" });

The makeRequest function remains reusable for any response type while staying typesafe.

These examples illustrate TypeScript's capabilities for building robust large-scale applications. Next let's look at how TypeScript delivers its unique advantages.

How TypeScript Provides Type Safety

TypeScript's compiler and tooling provide rock-solid type safety in multiple ways:

Static Analysis

The compiler analyzes code with types and catches mismatched values:

let price = "5";
let total = price + 5; // Error

Issues get surfaced early during development rather than silently causing bugs at runtime.

Contextual Typing

Types are inferred in many cases based on context:

let messages = ["Hello", "World"]; // String[] 

messages.push(5); // Error

Without explicit types, values are checked based on assignment and usage.

Gradually Strengthen Checking

The noImplicitAny and strict compiler flags enable progressively stricter checking. Bugs can be found by incrementally "tightening" code.

Editor Integration

Editors leverage compiler logic to highlight issues, provide autocomplete, and more based on types that are checked.

Combined with TypeScript's understanding of JavaScript semantics, these approaches deliver an unmatched level of type safety for variable code.

Editor Tooling with TypeScript

Given TypeScript's typing system, editors can offer intelligent coding assistance and program analysis:

Let's see examples of superb tooling experiences enabled:

Accurate Autocomplete

Autocomplete suggestions are context-aware:

Only relevant methods and signatures are shown based on types in scope. No more guessing!

Helpful Documentation

Hovering over identifiers reveals useful inline documentation:

Seeing types and doc comments directly in the editor improves speed and understanding.

Robust Refactoring

Renaming variables and methods just works:

The compiler handles updating all references to match. Refactoring is safe and fluid.

AI Code Completions

Models can suggest highly relevant completions powered by types:

AI smarts increase development velocity and reduce cognitive load.

TypeScript unlocks editor tooling that is incredibly useful for productivity and correctness. The typing system enables building the future of coding assistance.

Adoption by Frameworks and Platforms

Given TypeScript's advantages, it has been broadly adopted across the JavaScript ecosystem:

Angular

The Angular team at Google helped evolve TypeScript with features like decorators. Angular heavily leverages TS for its framework and requires it for Angular apps.

React

Facebook adopted TypeScript for internal React projects in 2017. The React+TypeScript combo is now popular for component architecture.

Vue

Vue 3 introduced TypeScript support and converts Vue core to TypeScript. It is becoming the standard for typed Vue applications.

Node.js

Node.js applications benefit from TypeScript at scale. Popular Node frameworks like Nest provide first-class TS support.

Deno

Deno is a new runtime built on TypeScript and V8 to replace Node.js. It uses TS instead of JS for more robustness.

NativeScript

NativeScript offers cross-platform mobile development using Angular and TypeScript with native UI components.

TypeScript's flexible any-to-any transpilation helped it gain widespread ecosystem adoption.

TypeScript in the Industry

Given TypeScript's ability to scale development, it has been embraced by many major tech companies:

Microsoft

Microsoft relies on TypeScript for its own products like Office, Visual Studio, Windows, and more. The team contributes significantly to TypeScript itself.

Google

Google adopted TypeScript for key applications like Google Docs and Google Analytics. Angular's continued TypeScript support also helps its usage at Google.

Facebook

Facebook uses TypeScript pervasively including for the React codebase. They contribute to improving TS integration with React.

Amazon

Amazon transitioned Amazon Music, Audible, and other flagship products to TypeScript. AWS SDKs also offer TypeScript definitions.

Apple

Apple adopted TypeScript for iTunes and iCloud applications. Xcode supports TypeScript for iOS development.

As complex web apps become increasingly critical, TypeScript's benefits make it a natural enterprise choice. Understanding TypeScript unlocks opportunities given its ubiquitous usage.

Potential Growth

TypeScript has seen exponential growth already, but still has room for further expansion in areas like:

- Replacing JavaScript at more companies

- Winning over remaining skeptics in the JavaScript community

- Becoming the standard language for front-end web development

-Expanding its tooling ecosystem further

Microsoft is investing heavily so TypeScript is poised for even wider adoption.

TypeScript Community

TypeScript has one of the largest and friendliest developer communities. Connecting with other users helps learn best practices and stay updated:

Awesome TypeScript Resources

Here are great next steps to continue mastering TypeScript:

Conferences and Meetups

Major conferences like TSConf attract thousands of TypeScript developers

Local TypeScript Meetup groups worldwide provide opportunities to learn and engage:

Find a Meetup

Forums and Training Courses

Active forums like Reddit and Discord offer help from knowledgeable developers:

Structured online courses offer guided learning paths:

TypeScript Courses on Frontend Masters

With a vibrant community, there are plenty of ways to continue mastering TypeScript.

The Future of TypeScript

TypeScript is already a mature language but continues rapid advancement with 2-3 major releases per year:

Some upcoming developments include:

  • Improvement of type inference and checking precision

  • Making compiler errors more accurate and tractable

  • Support for web frameworks and libraries

  • Expanded AI-assisted tooling

  • Integration into more platforms and backends

Given TypeScript's open governance model and focus on developer productivity, it is sure to thrive in the future. JS developers would benefit greatly from staying up.

Go Forth and TypeScript!

That wraps up this comprehensive starter guide to TypeScript. You should now have a great foundation to start leveraging TypeScript in your own projects.

TypeScript's combination of familiarity, versatility and tooling make it an essential part of any modern web developer's skillset. The benefits only continue to grow as applications increase in complexity.

So get out there, develop awesome TypeScript apps, and become part of the vibrant TS community!

Did you find this article valuable?

Support Mikey's Blog by becoming a sponsor. Any amount is appreciated!