TechLearn Hub

Learn Technology in Simple English

What Is TypeScript? A Beginner's Guide

TypeScript is a programming language developed by Microsoft. It builds on JavaScript and adds features such as static type checking, helping developers find many programming mistakes and maintain larger applications.

Simple definition: TypeScript is JavaScript with an additional type system and development tools. TypeScript code is normally transformed into JavaScript before it runs in a browser or JavaScript runtime.

What Is TypeScript?

TypeScript is a programming language built on JavaScript. It adds a type system that lets developers describe the kinds of values variables, function parameters, and return values are expected to use.

These type descriptions help editors and the TypeScript compiler identify many mistakes while developers are writing code. TypeScript also supports JavaScript features and can be used with much of the JavaScript ecosystem.

TypeScript types are primarily checked during development and compilation. Most type annotations are removed when TypeScript is transformed into JavaScript, so they do not automatically validate data while a program runs.

Who Created TypeScript?

TypeScript was developed by Microsoft and first made publicly available in 2012. It was created to help developers build and maintain large JavaScript applications while continuing to use the JavaScript ecosystem.

Today, TypeScript is commonly used in frontend applications, backend services, developer tools, and large codebases.

Why Is TypeScript Important?

As applications grow, developers need to understand what kind of information functions expect and what results they return. TypeScript helps make these expectations visible in the code.

TypeScript and JavaScript

TypeScript extends JavaScript with a type system and additional development features. A TypeScript project usually includes a step that transforms TypeScript source into JavaScript.

FeatureJavaScriptTypeScript
Type systemDynamic typingStatic type checking available
ExecutionRuns in supported JavaScript environmentsUsually transformed into JavaScript first
Editor supportStrong editor support availableAdditional type-aware assistance
Learning curveGood starting pointIncludes extra type-system concepts
EcosystemBroad web and server ecosystemUses the JavaScript ecosystem

TypeScript does not replace JavaScript. Learning JavaScript fundamentals makes it much easier to understand TypeScript.

Installing TypeScript

TypeScript is commonly installed using npm, the package manager distributed with Node.js. First install a suitable version of Node.js, then open a terminal.

To install the compiler globally, run:

npm install -g typescript

Check the installed version:

tsc --version

You can also install TypeScript locally in a project. A local installation helps a project use a specific compiler version:

npm install --save-dev typescript

A local compiler can be run through npm scripts or with npx tsc.

Your First TypeScript Program

Create a file called hello.ts:

let message: string = "Hello, TypeScript!";

console.log(message);

The .ts extension identifies the file as TypeScript source. The annotation : string says that the variable should contain a string.

Compile the file

tsc hello.ts

With the default settings, the compiler typically creates a corresponding JavaScript file named hello.js. You can then run the JavaScript using a suitable runtime, such as Node.js:

node hello.js
Remember: The TypeScript compiler checks types and transforms TypeScript syntax. Browsers generally execute JavaScript, not ordinary TypeScript source files directly.

Variables in TypeScript

TypeScript supports JavaScript variable declarations, including let and const. The older var keyword is also supported, but let and const are usually preferred in modern code.

let name: string = "Ahmed";
let age: number = 25;
const country: string = "Nigeria";

console.log(name, age, country);

Use let when a variable needs to be reassigned and const when the variable binding should not be reassigned.

Basic Data Types

TypeScript provides types for common JavaScript values and allows you to define more complex structures.

TypeExamplePurpose
string"Hello"Text
number25Numbers, including integers and decimals
booleantrueTrue or false values
number[][10, 20, 30]An array of numbers
object{ name: "Ali" }Non-primitive object values
anylet value: anyDisables many type checks for that value
unknownlet value: unknownRequires checks before safe use
voidfunction log(): voidCommonly used for functions with no meaningful return value
null and undefinedundefinedRepresent missing or absent values

Strings

let firstName: string = "Ali";
let message: string = "Welcome " + firstName;

console.log(message);

Numbers

let age: number = 30;
let price: number = 1500.50;

Booleans

let isLoggedIn: boolean = true;
let isAdmin: boolean = false;

Arrays

You can specify the type of items stored in an array:

let scores: number[] = [10, 20, 30];
let names: string[] = ["Ali", "Aisha", "Umar"];

Another array syntax uses generics:

let scores: Array<number> = [10, 20, 30];

Tuples

A tuple describes an array with a known sequence of element types:

let user: [string, number] = ["Ali", 25];

Here, the first element is a string and the second is a number.

Object Types

You can describe the expected structure of an object:

let product: {
  name: string;
  price: number;
} = {
  name: "Phone",
  price: 250000
};

Any and Unknown

The any type allows many operations without normal type checking. Overusing it removes much of TypeScript's benefit.

The unknown type is safer for values whose type is not yet known because you must check or narrow the value before using it as a specific type.

let input: unknown = "Hello";

if (typeof input === "string") {
  console.log(input.toUpperCase());
}

Type Inference

You do not need to write a type annotation for every variable. TypeScript can often infer the type from the initial value.

let age = 25;
let name = "Ali";

age = 30;
name = "Aisha";

// These would cause type errors:
// age = "thirty";
// name = 100;

Type inference helps keep code concise while preserving type checking.

Functions in TypeScript

Functions can specify types for their parameters and return values.

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

console.log(add(10, 20));

The parameter annotations require numeric arguments, while : number describes the return type.

Optional Parameters

A question mark marks a parameter as optional:

function greet(name?: string): void {
  if (name) {
    console.log("Hello " + name);
  } else {
    console.log("Hello!");
  }
}

greet("Ali");
greet();

Default Parameters

function welcome(name: string = "Guest"): string {
  return "Welcome, " + name;
}

console.log(welcome());
console.log(welcome("Aisha"));

Arrow Functions

const multiply = (a: number, b: number): number => {
  return a * b;
};

console.log(multiply(4, 5));

Union Types

A union type allows a value to have one of several specified types:

let id: string | number;

id = 100;
id = "ABC100";

When using a union, check the value before performing an operation that only works with one of its possible types.

function printId(id: string | number): void {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id);
  }
}

Type Aliases

Type aliases give a reusable name to a type:

type UserID = string | number;

let userId: UserID = 100;
let anotherId: UserID = "USER-20";

Literal Types

Literal types restrict a value to a specific set of allowed values:

type Status = "pending" | "approved" | "rejected";

let orderStatus: Status = "pending";

Interfaces

Interfaces describe the expected shape of an object. They are often used to define data structures and function parameters.

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

const user: User = {
  name: "Ali",
  age: 25
};

Optional Properties

Add a question mark to a property that does not have to be provided:

interface User {
  name: string;
  age?: number;
}

const user: User = {
  name: "Aisha"
};

Readonly Properties

The readonly modifier prevents a property from being reassigned through that typed property after initialization. It does not automatically make nested objects deeply immutable at runtime.

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

const user: User = {
  id: 1,
  name: "Ali"
};

user.name = "Umar";

// TypeScript error:
// user.id = 2;

Interface vs Type Alias

Both interfaces and type aliases can describe many object shapes. Interfaces can be extended and can participate in declaration merging, while type aliases can also represent unions, intersections, and other types.

Type Narrowing and Type Guards

Type narrowing means checking a value so TypeScript can understand which type is being used in a particular section of code.

function formatValue(value: string | number): string {
  if (typeof value === "number") {
    return value.toFixed(2);
  }

  return value.toUpperCase();
}

The typeof check narrows the union to a number in one branch and a string in the other.

Classes in TypeScript

TypeScript supports JavaScript classes and adds type annotations and other features that help describe class members.

class Person {
  name: string;

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

  greet(): void {
    console.log("Hello " + this.name);
  }
}

const person = new Person("Ali");
person.greet();

Inheritance

A class can extend another class and inherit its available behavior:

class Animal {
  move(): void {
    console.log("Moving");
  }
}

class Dog extends Animal {
  bark(): void {
    console.log("Woof!");
  }
}

const dog = new Dog();
dog.move();
dog.bark();

Access Modifiers

These TypeScript access modifiers are not all equivalent to runtime security controls. Use proper application security practices to protect sensitive data and operations.

Generics

Generics allow reusable functions, classes, and interfaces to work with different types while preserving useful type information.

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

const numberValue = identity<number>(10);
const textValue = identity<string>("Hello");

In this example, T represents a type chosen when the function is used. TypeScript can often infer the generic type automatically:

const first = identity(10);
const second = identity("Hello");

A Generic Array Function

function firstItem<T>(items: T[]): T | undefined {
  return items[0];
}

const firstName = firstItem(["Ali", "Aisha"]);
const firstScore = firstItem([10, 20, 30]);

Generics are useful when writing reusable code that should retain the type of the values passed into it.

Enums

Enums provide named constants. Numeric enums assign numeric values by default, while string enums use explicit string values.

enum Direction {
  Up,
  Down,
  Left,
  Right
}

const direction: Direction = Direction.Up;

For many applications, string literal unions are another useful option:

type DirectionName = "up" | "down" | "left" | "right";

const directionName: DirectionName = "up";

Type Assertions

A type assertion tells TypeScript to treat a value as a particular type. It does not perform runtime validation or change the value by itself.

let value: unknown = "Hello";

if (typeof value === "string") {
  const text = value;
  console.log(text.toUpperCase());
}

When you have a valid reason to assert a type, TypeScript also supports the as syntax:

const element = document.getElementById("title") as
  HTMLHeadingElement | null;

Use assertions carefully. An incorrect assertion can hide a problem rather than solve it.

Modules and Imports

Modules allow you to split code into separate files and share functions, types, and values between them.

In math.ts:

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

export interface Point {
  x: number;
  y: number;
}

In another file:

import { add, type Point } from "./math";

const result = add(10, 20);

const point: Point = {
  x: 5,
  y: 8
};

The import path and module resolution behavior depend on your project's compiler configuration and runtime or bundler.

TypeScript Configuration

A TypeScript project commonly uses a file named tsconfig.json to configure the compiler.

Settings may control:

Example tsconfig.json

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

This is an example configuration, not a universal setting. The appropriate module format and other options depend on whether you are building for a browser, Node.js, or another environment.

Strict Mode

Enabling "strict": true turns on a group of stronger type checking options. This helps identify more potential problems during development.

TypeScript and Web Development

TypeScript is widely used for websites, browser applications, dashboards, and business systems. It can be used with HTML, CSS, JavaScript, and frontend frameworks.

TypeScript itself does not replace HTML or CSS. HTML defines page structure, CSS controls presentation, and JavaScript provides application behavior. TypeScript adds a type system to the JavaScript development workflow.

TypeScript and React

TypeScript is commonly used with React. It can describe component props, event handlers, state, and data passed between components.

type ButtonProps = {
  text: string;
};

function Button({ text }: ButtonProps) {
  return <button>{text}</button>;
}

export default Button;

In this example, ButtonProps says that the component expects a string property named text. This example uses JSX, so the file is commonly saved with a .tsx extension.

TypeScript and Node.js

TypeScript can be used for backend development with Node.js and compatible tools. Developers can build APIs, web servers, scripts, and command-line applications.

A backend project often uses TypeScript with a framework, validation libraries, testing tools, and a database client. The runtime setup depends on the Node.js version and the project's build tools.

TypeScript and Databases

TypeScript applications can communicate with databases through backend libraries and database tools. A typical architecture may include:

TypeScript types can help describe data structures, but they do not automatically prove that data received from a database or external service is valid. Applications should handle untrusted data carefully.

TypeScript and APIs

TypeScript can be used to create APIs and consume information from other services. Developers often define types for the data an API is expected to return.

interface Product {
  id: number;
  name: string;
  price: number;
}

async function getProducts(): Promise<Product[]> {
  const response = await fetch("/api/products");

  if (!response.ok) {
    throw new Error("Failed to fetch products");
  }

  return response.json() as Promise<Product[]>;
}
Important: The type assertion in this example does not validate the actual JSON response. For external or untrusted data, use runtime validation before treating the response as a trusted Product[].

TypeScript and JSON

JSON is a common format for exchanging data. TypeScript interfaces can describe the expected shape of that data.

interface Product {
  id: number;
  name: string;
  price: number;
}

const product: Product = {
  id: 1,
  name: "Phone",
  price: 250000
};

An interface helps check code written in TypeScript. It does not automatically check that arbitrary JSON loaded at runtime matches the interface.

TypeScript for Large Applications

One reason teams use TypeScript is that explicit types can make large codebases easier to understand. Developers can inspect a function's parameters, return type, and data structures using their editor.

TypeScript can also help identify places that need updating when a type or function signature changes. The benefits depend on how consistently types are designed and maintained.

Advantages of TypeScript

Challenges of TypeScript

TypeScript vs JavaScript

FeatureJavaScriptTypeScript
TypingDynamicStatic type checking available
Build stepNot always requiredUsually transformed before execution
Editor assistanceAvailableAdditional type-aware assistance
LearningCore starting pointBuilds on JavaScript knowledge
Best useProjects of many sizesProjects that benefit from type checking

TypeScript vs Python

TypeScript and Python are different programming languages designed for different ecosystems and workflows.

TypeScript is closely connected to JavaScript and is widely used for web frontends, Node.js services, and JavaScript-based tools. Python is commonly used for automation, data science, artificial intelligence, scripting, and backend development.

Neither language is best for every task. Choose according to your project, available tools, and learning goals.

TypeScript Development Tools

What Can You Build With TypeScript?

How to Learn TypeScript

If you are a beginner, learn JavaScript fundamentals before or alongside TypeScript. This makes the language's additional type features easier to understand.

  1. Learn HTML page structure.
  2. Learn CSS and responsive design.
  3. Learn JavaScript variables, functions, arrays, and objects.
  4. Understand TypeScript's basic types and inference.
  5. Practice functions, union types, and type aliases.
  6. Learn interfaces and object types.
  7. Explore classes and generics.
  8. Learn modules and compiler configuration.
  9. Build small applications and test them.
  10. Explore React or Node.js if they match your goals.

Beginner TypeScript Projects

Small projects help you practise the concepts you have learned. Consider building:

Common TypeScript Mistakes

TypeScript and Security

TypeScript can help improve code quality, but it does not automatically make an application secure. Type checking is not a substitute for authentication, authorization, secure storage, or input validation.

Remember that TypeScript types generally do not exist in the emitted JavaScript. Treat data from users, network requests, and external services as untrusted until it has been validated.

TypeScript Cheat Sheet

ConceptExample
Stringlet name: string = "Ali";
Numberlet age: number = 25;
Booleanlet active: boolean = true;
Arraylet nums: number[] = [1, 2, 3];
Unionlet id: string | number;
Type aliastype ID = string | number;
Interfaceinterface User { name: string; }
Functionfunction add(a: number, b: number): number
Genericfunction identity<T>(value: T): T
Readonly propertyreadonly id: number;

Frequently Asked Questions

Is TypeScript a programming language?

Yes. TypeScript is a programming language developed by Microsoft that builds on JavaScript and adds static type checking.

Is TypeScript the same as JavaScript?

No. TypeScript adds a type system and other development features, but it remains closely connected to JavaScript.

Can TypeScript run directly in a browser?

Browsers generally execute JavaScript. TypeScript is usually transformed into JavaScript before browser execution.

Is TypeScript difficult to learn?

It can be easier to learn after understanding JavaScript fundamentals. Start with basic types and functions before moving to generics and advanced type features.

Can TypeScript be used for backend development?

Yes. It can be used with Node.js and compatible tools to build backend services, APIs, and command-line programs.

Can TypeScript be used with React?

Yes. TypeScript is commonly used with React to describe component props, state, events, and application data.

Can TypeScript be used for mobile applications?

Yes. It can be used with compatible JavaScript-based mobile frameworks and tools.

Does TypeScript prevent every programming error?

No. It can detect many type-related mistakes, but logic errors, network problems, invalid external data, and runtime failures can still occur.

Do I need Node.js to use TypeScript?

Node.js and npm are commonly used to install and run TypeScript development tools. Other development environments may offer different workflows.

Is TypeScript free?

Yes. TypeScript is an open-source project available for free.

Conclusion

TypeScript extends JavaScript with a type system and development features that help developers understand their code, catch many mistakes earlier, and maintain larger projects.

It is useful for frontend applications, backend services, APIs, and many other software projects. For most beginners, learning JavaScript fundamentals and then practising TypeScript is a practical approach.

Start with variables, basic types, and functions. Then move on to interfaces, generics, modules, and small projects. Consistent practice will help you build confidence and create more maintainable applications.

Your next step: Build a small TypeScript calculator or to-do application. Practise defining types, writing functions, and fixing compiler errors as you work.
↑ Back to top