What Is TypeScript and Why Is It Used?

Learn What Is TypeScript and Why Is It Used? with practical examples, explanations, best practices, and real-world coding techniques.

What Is TypeScript?

TypeScript is a programming language developed by Microsoft that builds on JavaScript by adding a static type system and additional development-time features. It allows developers to describe the kinds of values variables, function parameters, return values, and objects are expected to use.

JavaScript is a dynamically typed language, which means that variables can hold values of different types during execution. This flexibility is useful, but it can also allow certain mistakes to remain unnoticed until the relevant code runs. TypeScript helps identify many of these problems before an application is executed.

TypeScript is a superset of JavaScript in the sense that it supports JavaScript syntax and adds a type system and other language features. Most valid JavaScript code can be used in TypeScript, although some projects may require changes to module configuration, libraries, or type definitions when migrating.

TypeScript code is commonly checked and transformed into JavaScript before execution. Browsers and standard JavaScript runtimes generally execute the resulting JavaScript rather than TypeScript's type annotations. This allows developers to benefit from static type checking while targeting familiar JavaScript environments.

Why Was TypeScript Created?

JavaScript applications can grow to contain thousands of functions, modules, objects, and interconnected components. As a codebase becomes larger, understanding the expected structure of data and the behavior of each function becomes increasingly important.

TypeScript addresses these challenges by allowing developers to describe data structures explicitly, discover errors during development, and use editor features such as autocomplete and safer refactoring.

Consider a JavaScript function that calculates a total price:

function calculateTotal(price, quantity) {
  return price * quantity;
}

console.log(calculateTotal(100, 3));
console.log(calculateTotal("hello", 3));

JavaScript permits the second call, even though a string containing "hello" is not a meaningful price. The multiplication produces NaN, which can lead to incorrect calculations elsewhere in the application.

In TypeScript, you can declare the expected parameter types:

function calculateTotal(
  price: number,
  quantity: number
): number {
  return price * quantity;
}

console.log(calculateTotal(100, 3));

// Compile-time error:
// calculateTotal("hello", 3);

TypeScript reports the incompatible argument because the function expects numbers. This is one of its main benefits: detecting many type-related problems before the application runs.

JavaScript vs TypeScript

JavaScript and TypeScript share much of their syntax, but they differ in how they describe and check values during development. JavaScript relies primarily on runtime behavior, while TypeScript adds static analysis that can identify incompatible types before execution.

Feature JavaScript TypeScript
Type system Dynamic typing Static type checking with inference
Type annotations Not supported as standard JavaScript syntax Supported
Error detection Many problems are discovered at runtime or through other tools Many type errors can be detected before execution
Execution Runs in compatible JavaScript environments Usually transformed into JavaScript before execution
Editor support Available through language tooling Enhanced with type-aware autocomplete and refactoring
Large applications Can scale with appropriate engineering practices Adds type contracts that can help teams maintain larger codebases

TypeScript does not replace JavaScript. Instead, it provides additional tools for developing JavaScript applications. Developers can adopt TypeScript for a new project or migrate an existing JavaScript codebase gradually.

Key Benefits of TypeScript

1. Early error detection

Type checking identifies many incompatible assignments, incorrect arguments, and invalid property accesses during development, before the affected code is executed.

2. Better code completion

Editors can suggest available properties, methods, and function arguments based on the types in your code, reducing the need to remember every detail manually.

3. Improved maintainability

Explicit contracts make it easier to understand how modules interact and help developers identify code that needs updating after a type or interface changes.

4. Safer refactoring

When a function signature or shared model changes, the compiler can highlight many affected call sites that need to be reviewed.

5. Reusable contracts

Interfaces, type aliases, and generics allow developers to define and reuse data structures and function contracts across an application.

How TypeScript Works

TypeScript introduces a development and compilation step before the resulting JavaScript is executed. The compiler checks source code against the configured type rules and can generate JavaScript that is compatible with the selected target environment.

TypeScript source

app.ts

↓

Type checking and compilation

Compiler checks types and transforms supported syntax

↓

JavaScript output

app.js

↓

JavaScript runtime

Browser or compatible runtime such as Node.js

Consider this TypeScript declaration:

const courseName: string = "TypeScript";

The type annotation helps the compiler verify that the variable is assigned a compatible value. A typical JavaScript output is:

const courseName = "TypeScript";

The type annotation is removed because it is a TypeScript-only construct. Type annotations do not automatically create runtime validation or runtime type metadata.

Some development and build tools transpile TypeScript without performing full type checking. For that reason, projects may need a separate type-checking step even when their application builds successfully.

Installing TypeScript

To start using TypeScript in a local project, install Node.js and npm if they are not already available. npm is included with standard Node.js installations and can be used to manage the TypeScript compiler as a development dependency.

Open a terminal in your project directory and run:

npm init -y
npm install --save-dev typescript

The first command creates a basic package.json file when starting a new npm project. The second installs TypeScript locally in the project so team members and build pipelines can use the same declared compiler dependency.

Verify the installation:

npx tsc --version

The command reports the installed TypeScript compiler version. Using npx tsc from the project directory normally runs the locally installed compiler, helping keep development consistent across machines.

Your First TypeScript Program

After installing TypeScript, create a file named app.ts. The .ts extension identifies a TypeScript source file.

const language: string = "TypeScript";

function greet(name: string): string {
  return "Hello, " + name + "!";
}

console.log("Learning " + language);
console.log(greet("Developer"));

This program introduces two important features. The variable language has an explicit string type, while the greet() function declares the type of its parameter and its return value.

Compile the file:

npx tsc app.ts

When compilation succeeds with the default file-based behavior, TypeScript generates an app.js file in the same directory. Run the generated JavaScript with Node.js:

node app.js

For a real application, you will typically use a project configuration and possibly a framework build tool. This first example demonstrates the basic relationship between TypeScript source code, generated JavaScript, and execution.

Understanding Type Annotations

A type annotation explicitly declares the expected type of a variable, parameter, property, or return value. TypeScript uses a colon followed by the type name for many common annotations.

let courseTitle: string = "TypeScript Fundamentals";
let duration: number = 8;
let isPublished: boolean = true;

console.log(courseTitle);
console.log(duration);
console.log(isPublished);

In this example, the variables have declared types of string, number, and boolean. Assigning an incompatible value produces a type error during checking.

let courseCount: number = 10;

// Compile-time error:
// courseCount = "ten";

Type annotations are not required everywhere. TypeScript can infer many types from the values and expressions in your code. Use explicit annotations when they make a contract clearer or prevent an expression from being inferred more broadly than intended.

Understanding Type Inference

Type inference is TypeScript's ability to determine types automatically from the surrounding code. It reduces unnecessary annotations while allowing the compiler to check how values are used.

const courseName = "TypeScript";
// Inferred type: string

const duration = 8;
// Inferred type: number

const isAvailable = true;
// Inferred type: boolean

function addNumbers(first: number, second: number) {
  return first + second;
}

// Inferred return type: number
const total = addNumbers(10, 20);

console.log(courseName);
console.log(duration);
console.log(isAvailable);
console.log(total);

TypeScript infers the types of the first three variables from their initial values. It also infers the function's return type from the returned expression because both parameters are numeric.

Inference works especially well for local variables and simple functions. Explicit types remain valuable for public APIs, exported functions, shared data models, and complex behavior where the intended contract should be easy to understand.

Introduction to Basic TypeScript Types

TypeScript includes several fundamental types used to describe everyday JavaScript values. These types form the foundation for defining variables, function parameters, object structures, and reusable APIs.

string

Represents text values such as course titles, usernames, descriptions, and messages.

let username: string = "Asha";

number

Represents JavaScript numeric values, including integers and floating-point numbers.

let price: number = 49.99;

boolean

Represents true or false values used in conditions, settings, and status flags.

let isActive: boolean = true;

Array types

Represent collections whose elements follow a specified type.

let scores: number[] = [80, 90, 95];

Object types

Describe the properties and their types in structured values.

let course: { title: string; duration: number } = {
  title: "TypeScript",
  duration: 8
};

As you progress, you will also learn union types, literal types, interfaces, type aliases, generics, and more advanced type system features for modelling complex applications.

Working with Objects and Interfaces

Applications frequently work with structured information such as users, courses, products, and orders. TypeScript allows you to define the expected properties of these objects through object types, interfaces, and type aliases.

interface Course {
  id: number;
  title: string;
  duration: number;
  published: boolean;
}

const course: Course = {
  id: 101,
  title: "TypeScript Fundamentals",
  duration: 8,
  published: true
};

function displayCourse(value: Course): void {
  console.log(value.title);
  console.log(value.duration);
}

displayCourse(course);

The Course interface defines a reusable contract. Objects assigned to this type must contain the required properties with compatible values. The function can then rely on the properties declared by the interface.

Interfaces and type aliases become especially useful in larger projects where multiple components, services, and functions need to agree on the shape of shared data.

Configuring a TypeScript Project

A TypeScript project commonly uses a file named tsconfig.json to define compiler options and identify the files that belong to the project. The configuration controls settings such as the JavaScript target, module system, type-checking strictness, and output behavior.

Generate an initial configuration with:

npx tsc --init

A simplified configuration for a basic project might look like this:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "strict": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "noEmitOnError": true
  },
  "include": ["src/**/*"]
}

This example assumes a simple project using CommonJS-style modules. Browser applications, modern Node.js projects using ECMAScript modules, and framework-managed applications may require different options. The package configuration, runtime, and build tool should agree on the module format.

The strict option enables a collection of stricter type checks. The rootDir and outDir options organize source files and generated JavaScript. The noEmitOnError option prevents compiler output from being generated when TypeScript reports errors during compilation.

Compiling and Running TypeScript

When working directly with the TypeScript compiler, you can compile an individual file or build a project using its configuration.

To compile a single file:

npx tsc app.ts

To compile according to the project configuration, run:

npx tsc

Compile a configured project from its root directory, then execute the generated JavaScript using the appropriate runtime. When passing source filenames directly to tsc, the compiler uses command-line behavior rather than automatically applying every setting from the project's tsconfig file. For project-specific builds, invoking the compiler without input filenames is generally the expected workflow.

Framework projects may use tools such as Angular's compiler or a JavaScript bundler to process TypeScript. In those environments, follow the framework's build workflow and make sure type checking is enabled where required.

TypeScript Does Not Replace Runtime Validation

TypeScript provides static type checking, but type annotations are normally removed from the generated JavaScript. They do not automatically verify data received from an API, browser storage, a JSON file, or an untrusted external source.

For example, declaring an API response as a User does not prove that the server actually returned a valid User object. If the data structure is different, the application can still encounter runtime errors.

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

function isUser(value: unknown): value is User {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  if (!("id" in value) || !("name" in value)) {
    return false;
  }

  return (
    typeof value.id === "number" &&
    typeof value.name === "string"
  );
}

const input: unknown = {
  id: 1,
  name: "Asha"
};

if (isUser(input)) {
  console.log(input.name.toUpperCase());
}

The type guard checks the properties needed by the application before treating the value as a User. Real applications may need more comprehensive validation for nested fields, allowed values, and business rules.

This distinction is important: static types help developers write safer code, while runtime validation checks whether actual values satisfy the requirements at execution time.

Where Is TypeScript Used?

TypeScript can be used in different kinds of JavaScript applications. It is not restricted to a single framework or runtime, and its static type system is useful wherever developers need reliable contracts between pieces of code.

  • Frontend development: Build web applications using Angular, React, Vue, and other compatible tools.
  • Backend development: Create APIs, services, command-line tools, and server applications running on compatible JavaScript runtimes.
  • Libraries and SDKs: Publish reusable packages with well-defined public types.
  • Full-stack applications: Share suitable types between frontend and backend packages while keeping runtime boundaries and validation in mind.
  • Large team projects: Make contracts more explicit and help developers navigate interconnected modules.

The language is most useful when its type system is integrated into the development workflow rather than treated as a separate documentation step. Good compiler settings, meaningful types, tests, and code reviews help the benefits carry through to production development.

Common Beginner Mistakes

Assuming types exist at runtime

Type annotations are normally erased during compilation. Use runtime checks when external values must be validated.

Using any for every variable

The any type disables many useful checks. Prefer meaningful types and learn to use unknown when the type has not yet been established.

Annotating every obvious value

Type inference already handles many straightforward declarations. Add explicit types when they clarify the intended contract or improve reliability.

Ignoring compiler errors

Type errors often indicate a mismatch between how a value is used and how it is defined. Understand and resolve the underlying issue instead of automatically suppressing it.

Assuming a successful build proves correctness

Type checking catches many classes of errors, but it does not replace tests, runtime validation, or checks for application-specific behavior.

What to Learn After TypeScript Basics

After understanding TypeScript's purpose, setup, basic types, and compiler workflow, continue by learning how to describe more complex application data and control how values are used.

  • Primitive types, arrays, and tuples.
  • Type annotations and type inference.
  • Interfaces and type aliases.
  • Functions, callbacks, and function signatures.
  • Union types, literal types, and type narrowing.
  • Classes, access modifiers, and inheritance.
  • Generics and utility types.
  • Modules, imports, exports, and compiler configuration.
  • Error handling, runtime validation, and TypeScript best practices.

Learn these concepts gradually by writing small programs and reviewing compiler errors. Practical experience helps you understand not only how TypeScript syntax works, but also how its type system helps organize real applications.

Conclusion

TypeScript extends JavaScript with static type checking, type annotations, inference, and reusable type definitions. These features help developers detect many errors earlier, document function contracts, improve editor support, and maintain complex applications more confidently.

Begin by installing TypeScript, writing a simple program, and experimenting with basic types and function signatures. As your understanding grows, explore interfaces, generics, unions, modules, and strict compiler settings. Combining these features with tests and runtime validation provides a strong foundation for building reliable TypeScript applications.

Code Examples

Your First TypeScript Program

typescript
const language: string = "TypeScript";

function greet(name: string): string {
  return "Hello, " + name + "!";
}

console.log("Learning " + language);
console.log(greet("Developer"));
    

This program introduces string annotations, typed function parameters, and a return type. TypeScript checks that the implementation follows the declared contracts.

Basic Type Annotations

typescript
let courseTitle: string = "TypeScript Fundamentals";
let duration: number = 8;
let isPublished: boolean = true;

console.log(courseTitle);
console.log(duration);
console.log(isPublished);

// Compile-time error:
// duration = "eight";
    

Annotations declare the kinds of values expected by variables and allow TypeScript to report incompatible assignments during type checking.

Type Inference

typescript
const courseName = "TypeScript";
const duration = 8;
const isAvailable = true;

function addNumbers(first: number, second: number) {
  return first + second;
}

const total = addNumbers(10, 20);

console.log(courseName);
console.log(duration);
console.log(isAvailable);
console.log(total);
    

TypeScript infers types from initial values and returned expressions, avoiding redundant annotations while preserving static checking.

Using Interfaces

typescript
interface Course {
  id: number;
  title: string;
  duration: number;
  published: boolean;
}

const course: Course = {
  id: 101,
  title: "TypeScript Fundamentals",
  duration: 8,
  published: true
};

function displayCourse(value: Course): void {
  console.log(value.title);
  console.log(value.duration);
}

displayCourse(course);
    

An interface describes a reusable object contract. Functions can accept that contract instead of depending on loosely structured objects.

Function Type Checking

typescript
function calculateTotal(
  price: number,
  quantity: number
): number {
  return price * quantity;
}

console.log(calculateTotal(100, 3));

// Compile-time error:
// calculateTotal("hello", 3);
    

TypeScript verifies function arguments against the declared parameters and catches incompatible values before the application executes.

Pro Tip

Learn TypeScript by writing small JavaScript-style programs and progressively adding accurate types. Enable strict checking early, use type inference when it keeps code clear, and remember that compiler checks complement rather than replace runtime validation and automated tests.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.