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.
Table of Contents
- What Is TypeScript?
- Who Created TypeScript?
- TypeScript and JavaScript
- Installing TypeScript
- Your First Program
- Basic Data Types
- Type Inference
- Functions
- Union Types and Aliases
- Interfaces and Objects
- Classes and Inheritance
- Generics
- Modules and Configuration
- TypeScript with React
- TypeScript with Node.js
- Advantages and Challenges
- Beginner Projects
- TypeScript and Security
- Cheat Sheet
- Frequently Asked Questions
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.
- It can detect many type-related mistakes before runtime.
- It improves code completion and editor assistance.
- It makes function contracts easier to understand.
- It supports safer refactoring in many situations.
- It works with JavaScript libraries and frameworks.
- It can improve the maintainability of large projects.
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.
| Feature | JavaScript | TypeScript |
|---|---|---|
| Type system | Dynamic typing | Static type checking available |
| Execution | Runs in supported JavaScript environments | Usually transformed into JavaScript first |
| Editor support | Strong editor support available | Additional type-aware assistance |
| Learning curve | Good starting point | Includes extra type-system concepts |
| Ecosystem | Broad web and server ecosystem | Uses 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
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.
| Type | Example | Purpose |
|---|---|---|
string | "Hello" | Text |
number | 25 | Numbers, including integers and decimals |
boolean | true | True or false values |
number[] | [10, 20, 30] | An array of numbers |
object | { name: "Ali" } | Non-primitive object values |
any | let value: any | Disables many type checks for that value |
unknown | let value: unknown | Requires checks before safe use |
void | function log(): void | Commonly used for functions with no meaningful return value |
null and undefined | undefined | Represent 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
publicallows normal access to a member.protectedallows access within the class and subclasses.privaterestricts access through TypeScript's type system.
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:
- The JavaScript language target.
- Module format and module resolution.
- Strict type checking.
- Input and output directories.
- Which files are included in compilation.
- How JavaScript and type declaration files are handled.
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:
- A TypeScript application or API.
- Server-side business logic.
- Input validation and authentication.
- A database client or data access layer.
- A database such as PostgreSQL, MySQL, or MongoDB.
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[]>;
}
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
- Static type checking during development.
- Better type-aware editor suggestions.
- Clearer function and data contracts.
- Useful tooling for refactoring.
- Compatibility with much of the JavaScript ecosystem.
- Support for modern JavaScript syntax and patterns.
- Useful for large teams and applications.
Challenges of TypeScript
- There are additional concepts to learn.
- Many projects need a build or transformation step.
- Complex types can be difficult to understand.
- Third-party libraries may have incomplete or outdated type definitions.
- Type annotations do not replace runtime validation.
- Incorrect assertions can hide errors from the type checker.
TypeScript vs JavaScript
| Feature | JavaScript | TypeScript |
|---|---|---|
| Typing | Dynamic | Static type checking available |
| Build step | Not always required | Usually transformed before execution |
| Editor assistance | Available | Additional type-aware assistance |
| Learning | Core starting point | Builds on JavaScript knowledge |
| Best use | Projects of many sizes | Projects 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
- Visual Studio Code: A code editor with TypeScript support.
- Node.js: A JavaScript runtime often used for development tools and servers.
- npm: A package manager for installing dependencies.
- TypeScript compiler: Checks types and transforms TypeScript.
- Browser developer tools: Help inspect and debug browser applications.
- Git: Tracks changes to source code.
What Can You Build With TypeScript?
- Web applications and dashboards.
- Backend APIs and services.
- Business and productivity tools.
- Browser games.
- Command-line utilities.
- Mobile applications using compatible development frameworks.
- Desktop applications using supported JavaScript technologies.
- Developer tools and automation scripts.
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.
- Learn HTML page structure.
- Learn CSS and responsive design.
- Learn JavaScript variables, functions, arrays, and objects.
- Understand TypeScript's basic types and inference.
- Practice functions, union types, and type aliases.
- Learn interfaces and object types.
- Explore classes and generics.
- Learn modules and compiler configuration.
- Build small applications and test them.
- 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:
- Calculator: Practise functions and numeric values.
- To-do app: Model tasks using interfaces.
- Quiz app: Define question and answer types.
- Expense tracker: Work with arrays and data structures.
- Notes app: Practise editing and displaying typed data.
- Weather app: Fetch and validate external API data.
- Dashboard: Build reusable components and types.
- Simple API: Practise backend routes and request handling.
Common TypeScript Mistakes
- Using
anyeverywhere and losing useful type checks. - Ignoring compiler errors instead of understanding them.
- Using type assertions without checking the actual data.
- Making types unnecessarily complicated.
- Assuming interfaces validate data at runtime.
- Forgetting that most TypeScript type annotations are erased from JavaScript output.
- Skipping JavaScript fundamentals.
- Assuming successful compilation guarantees an error-free application.
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.
- Never expose private API keys or passwords in frontend code.
- Validate untrusted input on the server.
- Check permissions before allowing sensitive operations.
- Validate external API and database data at runtime when needed.
- Keep dependencies updated and review security advisories.
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
| Concept | Example |
|---|---|
| String | let name: string = "Ali"; |
| Number | let age: number = 25; |
| Boolean | let active: boolean = true; |
| Array | let nums: number[] = [1, 2, 3]; |
| Union | let id: string | number; |
| Type alias | type ID = string | number; |
| Interface | interface User { name: string; } |
| Function | function add(a: number, b: number): number |
| Generic | function identity<T>(value: T): T |
| Readonly property | readonly 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.