JavaScript Integration

Back

Loading concept...

TypeScript Meets JavaScript: Building Bridges Between Worlds 🌉

Analogy: Think of TypeScript as a safety helmet and JavaScript as riding a bicycle. You can ride without a helmet, but the helmet protects you from falls. TypeScript lets you add that protection gradually—even to bikes you’ve been riding for years!


The Story: A Bicycle Shop’s Upgrade

Imagine you run a bicycle shop. You’ve been selling bikes (JavaScript) for years. Now, customers want helmets (TypeScript) for safety. The good news? You don’t need to throw away all your bikes! You can:

  1. Add helmet hooks to new bikes
  2. Slowly add hooks to old bikes
  3. Let some customers ride without helmets (but warn them!)

This is JavaScript Integration in TypeScript. Let’s explore how!


1. DOM Type Definitions: Talking to Web Pages 🖥️

What is it?

The DOM (Document Object Model) is how JavaScript talks to your webpage. TypeScript comes with built-in “dictionaries” that know every HTML element!

Simple Example

// TypeScript knows this is an HTMLButtonElement!
const btn = document.querySelector('button');

// It knows buttons have 'disabled'
if (btn) {
  btn.disabled = true;
}

Why is this cool?

Without types, you might write:

btn.dissabled = true; // Typo! No warning!

With TypeScript DOM types:

btn.dissabled = true;
// ❌ Error: 'dissabled' doesn't exist!

Real Life Example

// Get an input element
const input = document
  .getElementById('email') as HTMLInputElement;

// TypeScript knows .value exists!
console.log(input.value);

// TypeScript knows .checked is for checkboxes
const checkbox = document
  .querySelector('input[type="checkbox"]')
  as HTMLInputElement;
console.log(checkbox.checked);

2. Node.js Types: TypeScript on the Server 🖧

What is it?

Node.js runs JavaScript outside browsers. TypeScript needs special “dictionaries” to understand Node.js features like files and servers.

How to add them?

npm install @types/node

Simple Example

// Now TypeScript understands Node.js!
import * as fs from 'fs';
import * as path from 'path';

// TypeScript knows these functions
const filePath = path.join(__dirname, 'data.txt');
const content = fs.readFileSync(filePath, 'utf-8');

Before and After

Without @types/node:

import * as fs from 'fs';
// ❌ Cannot find module 'fs'

With @types/node:

import * as fs from 'fs';
// ✅ TypeScript knows fs.readFile,
//    fs.writeFile, and more!

3. JSDoc Annotations: Adding Types in Comments 📝

What is it?

JSDoc lets you add type information using comments. The code stays JavaScript, but TypeScript can read your hints!

The Magic Analogy

It’s like putting sticky notes on your bike: “This handle is for LEFT hand only!” The bike works the same, but now everyone knows the rules.

Simple Example

/**
 * Adds two numbers together
 * @param {number} a - First number
 * @param {number} b - Second number
 * @returns {number} The sum
 */
function add(a, b) {
  return a + b;
}

More JSDoc Patterns

/** @type {string} */
let username;

/** @type {number[]} */
let scores = [100, 95, 88];

/**
 * @typedef {Object} User
 * @property {string} name
 * @property {number} age
 */

/** @type {User} */
const person = { name: 'Alex', age: 25 };

4. @ts-check Directive: Safety for JavaScript Files ✅

What is it?

Add // @ts-check at the top of any JavaScript file, and TypeScript will check it for errors—without converting to .ts!

The Story

Remember our bicycle shop? This is like saying: “Check THIS bike for safety issues, but don’t change anything!”

Simple Example

// @ts-check

/** @type {number} */
let count = 0;

count = "hello";
// ❌ Type 'string' is not assignable
//    to type 'number'

Real Scenario

// @ts-check

/**
 * @param {string} name
 * @returns {string}
 */
function greet(name) {
  return 'Hello, ' + name;
}

greet(123);
// ❌ Argument of type 'number' is not
//    assignable to parameter type 'string'

5. @ts-ignore and @ts-expect-error: Emergency Overrides 🚨

What are they?

Sometimes TypeScript complains, but you know better. These directives tell TypeScript: “Trust me on this line!”

@ts-ignore: “Skip this line”

// @ts-ignore
const result = someUntypedLibrary.doThing();

@ts-expect-error: “I expect an error here”

// @ts-expect-error - Testing bad input
const x: number = "not a number";

The Difference

Directive What it does
@ts-ignore Silently skips errors
@ts-expect-error Expects an error; warns if none!

When to Use

// ✅ Good: You know this works
// @ts-ignore - Legacy library, no types
legacyLib.oldMethod();

// ✅ Good: Testing error cases
// @ts-expect-error - Testing invalid input
validateEmail(12345);

// ❌ Bad: Hiding real bugs!
// @ts-ignore
const broken = user.nmae; // Typo!

6. Migrating from JavaScript: The Journey 🚀

The Story

Your bicycle shop has 100 old bikes. You want to add safety helmets to all of them. Do you:

A) Close shop for a year? ❌ B) Upgrade one bike at a time? ✅

TypeScript migration works the same way!

Step-by-Step Migration

graph TD A["Start: Pure JavaScript"] --> B["Add tsconfig.json"] B --> C["Rename .js to .ts"] C --> D["Fix Type Errors"] D --> E["Add Stricter Rules"] E --> F["Fully Typed!"]

Step 1: Add tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": false,
    "outDir": "./dist",
    "strict": false
  },
  "include": ["src/**/*"]
}

Step 2: Start with @ts-check

// @ts-check
// Your existing JavaScript file

/** @type {string} */
let message = "Hello!";

Step 3: Rename files gradually

src/
├── utils.js      → utils.ts
├── api.js        → Keep as .js for now
└── app.js        → app.ts

Step 4: Enable strict mode slowly

{
  "compilerOptions": {
    "strict": false,
    "noImplicitAny": true,
    "strictNullChecks": true
  }
}

Migration Tips

Tip Why
Start with leaf files Files with no imports
Use any temporarily Remove later
Add JSDoc first Test before converting
Enable rules one by one Avoid 1000 errors!

Summary: Your JavaScript Integration Toolkit 🧰

graph LR A["JavaScript + TypeScript"] --> B["DOM Types"] A --> C["Node.js Types"] A --> D["JSDoc"] A --> E["@ts-check"] A --> F["@ts-ignore"] A --> G["Migration"] B --> H["Built-in!"] C --> I["npm install @types/node"] D --> J["Comments with types"] E --> K["Check JS files"] F --> L["Emergency escape"] G --> M["Gradual upgrade"]

You Did It! 🎉

You now know how to:

  • ✅ Use DOM types for web page elements
  • ✅ Add Node.js types for server code
  • ✅ Write JSDoc annotations in JavaScript
  • ✅ Enable @ts-check for JS file checking
  • ✅ Use @ts-ignore and @ts-expect-error wisely
  • Migrate from JavaScript to TypeScript gradually

Remember: TypeScript doesn’t force you to change everything at once. Like our bicycle shop, you can add safety features one bike at a time. The journey from JavaScript to TypeScript is a marathon, not a sprint! 🏃‍♂️


Pro Tip: Start with @ts-check and JSDoc today. You’ll catch bugs immediately—without changing any file extensions!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.