Skip to main content
← Back to Blog
2026-02-21 · 7 min readWeb DevelopmentUpdated Oct 29, 2026

Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects

A practical case for TypeScript. You turn a fragile JavaScript function into typed code, see the compiler flag a missing null check and a bad value, learn why unknown beats any, why types vanish at runtime, and how to add TypeScript to an existing project one file at a time.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
12 views
Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects

TypeScript catches a whole class of JavaScript bugs before the code runs: a missing property, a value that might be undefined, a typo in a field name. This guide is for JavaScript developers deciding whether TypeScript is worth the extra typing. You will convert a fragile function, see exactly what the compiler reports, and add TypeScript to a project one file at a time.

I was debugging a micro-SaaS backend at 2 AM. The error was the classic Cannot read property 'id' of undefined. Somewhere in a utility function, an object had a slightly different shape than the code expected. That is the kind of bug a type checker reports while you are still writing the code.

This is part 17 of the Frontend & JavaScript Fundamentals series. It follows frontend authentication with JWTs and cookies.

Key takeaways

  • TypeScript checks the shape of your data before the code runs, so a missing null check becomes an editor error instead of a crash.
  • Types are erased when the code is compiled. Data from APIs still needs a runtime check.
  • Use unknown, not any, when you don't know a type yet, and turn on strict from the start.

What TypeScript is

TypeScript is JavaScript plus a static type system: it describes the shapes of your values and warns you when the code uses them wrongly, before the program runs. The TypeScript handbook says your existing working JavaScript is already valid TypeScript. You add types where they help.

JavaScript checks types only at runtime. When you pass a variable around, you trust that it is a string or that the object has a user_id property. If the trust is wrong, the user sees the crash. TypeScript moves that check to compile time, where you see a red underline in your editor instead.

What you get beyond "types"

Code that documents itself

Here is a JavaScript function you wrote six months ago:

function processData(data, config) {
  // What is inside data?
  // What options does config accept?
  return data.value * config.multiplier;
}

To use it safely, you have to read the body or hunt down the callers. With TypeScript, the signature tells you:

interface MetricData {
  value: number;
  timestamp: Date;
}

interface Config {
  multiplier: number;
  currency: string;
}

function processData(data: MetricData, config: Config): number {
  return data.value * config.multiplier;
}

You know what goes in and what comes out without reading the implementation.

A safety net for renames

Requirements change. Say you rename name to fullName. In plain JavaScript, you search the codebase and hope you found every use. In TypeScript, you change the interface, and the compiler lists every line that still uses the old name.

interface Customer {
  fullName: string; // renamed from `name`
}

function greet(customer: Customer): string {
  return `Hi ${customer.name}`;
  // Error: Property 'name' does not exist on type 'Customer'.
}

Types vanish at runtime

The handbook is clear: type annotations never change how your program runs, and the compiler erases them. An interface can't check the JSON that comes back from an API or an LLM. Treat outside data as unknown and check it before you use it.

interface Order {
  id: number;
  total: number;
}

function isOrder(value: unknown): value is Order {
  return (
    typeof value === 'object' &&
    value !== null &&
    typeof (value as Order).id === 'number' &&
    typeof (value as Order).total === 'number'
  );
}

const data: unknown = JSON.parse('{"id": 7, "total": 42}');
if (isOrder(data)) {
  console.log(data.total); // safe: TypeScript now knows the shape
}

For larger shapes, a schema library such as Zod writes the check for you and infers the TypeScript type from the same schema.

Practical build: convert JavaScript to TypeScript

Here is a function that fetches a user and formats a greeting. It is valid JavaScript, but it is fragile.

The fragile JavaScript

// userProcessor.js

const getUser = (id) => {
  // Simulating an API call
  // In reality, this might return null or missing fields
  return {
    id: id,
    username: "dev_avnish",
    meta: {
      role: "admin"
    }
  };
}

const formatUser = (user) => {
  // Potential Error 1: What if user is null?
  // Potential Error 2: What if 'meta' is missing?
  // Potential Error 3: Typos (e.g., user.usrname)
  return `User ${user.username} is a ${user.meta.role}`;
}

const u = getUser(101);
console.log(formatUser(u));

If the API stops sending meta, formatUser throws a TypeError. If you misspell username, it quietly prints "undefined".

The TypeScript version

Start by describing the shape of the data with interfaces.

// userProcessor.ts

// 1. Define the shape of the data
interface UserMeta {
  role: 'admin' | 'editor' | 'viewer'; // Union type: restricts values to specific strings
  lastLogin?: Date; // Optional property
}

interface User {
  id: number;
  username: string;
  meta?: UserMeta; // The entire meta object is now optional
}

// 2. Apply types to functions
const getUser = (id: number): User => {
  return {
    id: id,
    username: "dev_avnish",
    meta: {
      role: "admin"
    }
  };
}

const formatUser = (user: User): string => {
  // Without the check below, TypeScript reports:
  // 'user.meta' is possibly 'undefined'.

  if (!user.meta) {
    return `User ${user.username} has no role assigned.`;
  }

  return `User ${user.username} is a ${user.meta.role}`;
}

const u = getUser(101);
console.log(formatUser(u));

What changed

  • Literal union type: role can only be 'admin', 'editor' or 'viewer'. Assigning "superadmin" gives the error "Type '"superadmin"' is not assignable to type '"admin" | "editor" | "viewer"'".
  • Optional property: meta? marks meta as possibly missing. The handbook says you must check an optional property for undefined before you read from it, so the compiler made you add the if (!user.meta) branch.
  • Return types: : User and : string state what each function promises. If a later edit returns the wrong shape, the error points at the function, not at some distant caller.

By default, tsc still writes the JavaScript file even when it finds type errors. The handbook suggests the noEmitOnError option if you want errors to block the output.

The any trap

When the compiler complains, it is tempting to silence it with any. The handbook says any disables all further type checking for that value. Use unknown instead: it accepts any value too, but you must narrow it before you use it.

// Avoid: any switches checking off, so this typo compiles
function shoutAny(data: any): string {
  return data.toUppercase();
}

// Prefer: unknown makes you check the type first
function shoutUnknown(data: unknown): string {
  if (typeof data === 'string') {
    return data.toUpperCase();
  }
  return '';
}

shoutAny compiles and then throws at runtime, because the real method is toUpperCase. shoutUnknown can't make that mistake.

Type What it accepts Checking When to use
any Anything Off for that value Short-term escape hatch while migrating
unknown Anything You must narrow before use Parsed JSON, API responses, catch-all parameters
A specific type or interface Only that shape Full Everything you can describe

Add TypeScript to an existing project

You don't need to rewrite the codebase. The migration guide starts with one file.

  1. Install: npm install typescript --save-dev
  2. Initialize: npx tsc --init creates a tsconfig.json.
  3. Migrate: rename one file from .js to .ts (or .tsx if it has JSX) and fix the errors. The allowJs option lets the rest stay JavaScript for now.

A small, strict tsconfig.json for a Node.js project, with your code in src/:

{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "strict": true,
    "allowJs": true,
    "rootDir": "src",
    "outDir": "dist",
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src"]
}

strict is the setting that matters most. It turns on the whole family of strict checks, including noImplicitAny and strictNullChecks, which catch the bug in this post. Recent versions of tsc --init already set it to true. allowJs lets your .ts files import the .js files you haven't converted yet, and rootDir with outDir sends the compiled files from src/ to dist/. The TSConfig reference suggests "module": "nodenext" for modern Node.js, as here, and "preserve" or "esnext" for code that a bundler builds.

Is the extra typing worth it?

TypeScript adds work up front. You type more characters, and you think about data shapes before logic. In return, a class of bugs shows up in your editor instead of in production, renames become safe, and new teammates can read a function's contract from its signature. For anything you will maintain for more than a few weeks, that trade usually pays off. Treat that as a rule of thumb, not a law.

Next in the series, getting started with React, JSX and components puts these types to use in UI code.

Frequently asked questions

Does TypeScript make my code run faster?

No. The compiler strips the types and outputs plain JavaScript, so runtime speed is the same. The gain is in catching bugs earlier and making refactors safer.

Do I still need runtime validation with TypeScript?

Yes, for any data that comes from outside your code: API responses, form input, files, LLM output. Types are erased at compile time, so they can't check what arrives at runtime. Type that data as unknown and validate it, by hand or with a library such as Zod.

What is the difference between any and unknown?

Both accept any value. any turns type checking off, so every operation is allowed. unknown allows nothing until you narrow it, for example with typeof or a type guard function.

Can I add TypeScript to an existing JavaScript project gradually?

Yes. Install TypeScript, enable allowJs, and rename files to .ts one at a time. Your existing JavaScript keeps working while you convert the files that matter most first.

Should I use interface or type?

The handbook says they are very similar and you can usually choose freely. Its suggestion is to use interface until you need a feature that only type offers, such as unions of different shapes.

Sources

Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.

  1. TypeScript Handbook: The Basics
  2. TypeScript Handbook: Everyday Types
  3. TypeScript Handbook: More on Functions (unknown)
  4. TypeScript Handbook: Narrowing
  5. TypeScript for JavaScript Programmers
  6. TypeScript: Migrating from JavaScript
  7. TSConfig Reference: strict
  8. Zod documentation
All 30 parts in this series
  1. Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
  2. Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
  3. Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
  4. Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
  5. Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
  6. Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
  7. Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
  8. Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
  9. Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
  10. Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
  11. Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
  12. Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
  13. Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
  14. Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
  15. Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
  16. Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
  17. Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
  18. Part 18Getting Started with React: Deconstructing JSX and Component Architecture
  19. Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
  20. Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
  21. Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
  22. Part 22React Architecture: Advanced Navigation and Data Flow Patterns
  23. Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
  24. Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
  25. Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
  26. Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
  27. Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
  28. Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
  29. Part 29Introduction to Micro Frontends: Building Scalable Architectures
  30. Part 30The Frontend Architecture: From Junior Developer to Tech Lead
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.