How Does TypeScript Work with JavaScript?

Learn How Does TypeScript Work with JavaScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to TypeScript and JavaScript Interoperability

TypeScript is built on JavaScript. It adds a static type system and development-time checks while preserving JavaScript's runtime behavior. TypeScript code is generally transformed into JavaScript before execution, allowing it to run in JavaScript environments such as browsers and Node.js.

TypeScript and JavaScript interoperability refers to the ability to use JavaScript modules, functions, libraries, and existing projects alongside TypeScript code. This capability is important because many applications already contain JavaScript files or depend on JavaScript packages that developers want to use without rewriting everything.

Instead of migrating an entire project at once, developers can introduce TypeScript gradually. They can enable JavaScript files in the TypeScript project, add type information through declaration files or JSDoc, and convert individual modules when doing so provides a practical benefit.

1. Understanding How TypeScript Works with JavaScript

JavaScript is the runtime language used by browsers and Node.js. TypeScript extends JavaScript syntax with features such as type annotations, interfaces, and generic types. Those TypeScript-specific type constructs are removed during compilation, leaving JavaScript that can execute in the target environment.

// TypeScript: greeting.ts
function greet(name: string): string {
  return "Hello, " + name;
}

console.log(greet("Asha"));

The type annotation on name and the return type are checked by TypeScript. They are not runtime validations and are not retained as JavaScript type annotations in ordinary TypeScript compilation.

// JavaScript output: greeting.js
function greet(name) {
  return "Hello, " + name;
}

console.log(greet("Asha"));

The compiled JavaScript can be consumed by other JavaScript modules and applications. TypeScript can also consume JavaScript modules, provided the project configuration and available type information support the intended usage.

Understanding this relationship is fundamental: TypeScript improves development-time safety, but JavaScript remains the runtime language for the emitted application code.

2. Importing JavaScript into TypeScript

Existing JavaScript modules can often be reused directly from TypeScript. For example, an application might already have a JavaScript utility that formats course names. A TypeScript file can import that utility rather than duplicating its implementation.

// formatter.js
export function formatCourseName(name) {
  return name.trim().toUpperCase();
}
// app.ts
import { formatCourseName } from "./formatter.js";

const courseName: string = formatCourseName("  TypeScript  ");

console.log(courseName);

In an ES module-based project, the JavaScript module exports its function and the TypeScript module imports it. The .js extension in the import path is appropriate for many modern ESM configurations, though the correct import path depends on the project's module system and build tooling.

The TypeScript compiler may infer types for JavaScript code, but inferred types can be limited when the implementation is dynamic or lacks explicit annotations. If the compiler reports that a JavaScript module cannot be resolved or lacks suitable type information, check the project configuration, the module path, and any available declaration files.

3. Enabling JavaScript Files in a TypeScript Project

The allowJs option in tsconfig.json lets JavaScript files participate in a TypeScript project. It is especially useful when an existing application contains both .js and .ts files.

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "allowJs": true,
    "strict": true,
    "noEmit": true
  },
  "include": ["src/**/*"]
}

In this example, allowJs permits JavaScript files to be included in the project. The noEmit setting prevents the TypeScript compiler from generating output files, which can be useful when another tool, such as a bundler, handles the build.

The exact configuration should match the application's build system. For example, a project that relies on tsc to emit JavaScript should not automatically use noEmit. A modern frontend project may instead use a bundler that processes TypeScript and JavaScript files together.

Enabling JavaScript does not automatically turn every JavaScript file into strictly checked TypeScript. Additional options control JavaScript checking and declaration generation, and their effects should be considered separately.

4. Checking JavaScript with checkJs

The checkJs option asks TypeScript to report many type errors in JavaScript files that are included in the project. It is particularly helpful during gradual migrations because existing JavaScript can receive additional checking without immediately being converted to TypeScript.

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "noEmit": true
  },
  "include": ["src/**/*"]
}

With checkJs enabled, TypeScript analyzes included JavaScript files and reports many issues it can identify from their code and available type information.

// calculate.js

/**
 * Adds two numeric values.
 * @param {number} first
 * @param {number} second
 * @returns {number}
 */
export function add(first, second) {
  return first + second;
}

add(10, 20);

// With JSDoc information available, this call
// is reported as a type error:
// add("10", 20);

JavaScript does not support TypeScript parameter annotations directly. JSDoc provides a way to describe the expected types using comments that TypeScript can understand.

checkJs is not a substitute for testing or runtime validation. Dynamic behavior, untyped external values, and situations beyond the compiler's static analysis can still produce runtime errors.

5. Using JSDoc to Add Type Information to JavaScript

JSDoc comments allow developers to describe types in JavaScript without introducing TypeScript syntax into the file. TypeScript can use these annotations to improve checking, editor suggestions, and information available when another file imports the JavaScript module.

// course.js

/**
 * @typedef {Object} Course
 * @property {number} id
 * @property {string} title
 * @property {boolean} published
 */

/**
 * Returns a course record.
 * @param {Course} course
 * @returns {string}
 */
export function getCourseTitle(course) {
  return course.title;
}

A TypeScript file can then import and use the JavaScript function:

// app.ts
import { getCourseTitle } from "./course.js";

const title = getCourseTitle({
  id: 101,
  title: "TypeScript Fundamentals",
  published: true
});

console.log(title);

JSDoc is useful when a team wants better type checking while keeping selected files in JavaScript. It also helps explain function contracts to developers who work with those modules.

Keep JSDoc annotations consistent with the actual implementation. Like TypeScript annotations, these comments do not automatically validate arbitrary runtime data or force JavaScript callers to follow the declared contract.

6. Understanding Declaration Files

Declaration files use the .d.ts extension. They describe the types exposed by JavaScript modules or libraries without providing their runtime implementation.

Declaration files are especially important when importing JavaScript that does not contain sufficient type information. A declaration can describe the exported functions, classes, properties, and types so that TypeScript can check how consumers use them.

// math-utils.d.ts
export declare function add(
  first: number,
  second: number
): number;

This declaration describes a function that exists in a corresponding JavaScript module:

// math-utils.js
export function add(first, second) {
  return first + second;
}

The TypeScript compiler can use the declaration to check imports and calls to add. The declaration does not implement the function and does not replace the JavaScript file at runtime.

Incorrect declarations can give consumers a false sense of safety, so declaration files must accurately reflect the real implementation. When declarations are generated automatically, verify that the output matches the public API you intend to expose.

7. Working with Third-Party JavaScript Libraries

Many npm packages are written in JavaScript, and TypeScript projects frequently depend on them. Some packages provide their own type declarations, while others rely on separate community-maintained declaration packages.

For libraries that publish their own TypeScript declarations, the compiler can often discover the types automatically. For supported packages whose declarations are maintained through DefinitelyTyped, the corresponding @types package may provide the missing type information.

// Example using a library with available types
import _ from "lodash";

const names = ["asha", "rahul", "maya"];
const sortedNames = _.sortBy(names);

console.log(sortedNames);

In a project that uses Lodash, appropriate package and type declarations must be installed and supported by the chosen module configuration. Package availability and the correct import form depend on the library version and project setup.

When TypeScript cannot find declarations for a JavaScript dependency, first check whether the package includes types, whether a compatible declaration package exists, and whether the dependency is being resolved through the intended module system.

Avoid immediately declaring an entire library as any. Doing so may suppress errors, but it removes much of the type information that makes TypeScript valuable.

8. Using TypeScript Code from JavaScript

JavaScript code can consume TypeScript functionality after the TypeScript module has been compiled, bundled, or otherwise made available as JavaScript. JavaScript cannot directly execute TypeScript-specific syntax in environments that do not support it.

// calculator.ts
export function multiply(
  first: number,
  second: number
): number {
  return first * second;
}

After compilation, the exported function is available through the generated JavaScript module. A JavaScript consumer can import it using the module format configured for the project.

// app.js in a compatible ESM project
import { multiply } from "./calculator.js";

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

The JavaScript caller does not receive TypeScript's static type checking merely by importing the function. The compiler can check TypeScript consumers against the declared signature, but ordinary JavaScript calls can still supply invalid values at runtime.

When exposing TypeScript libraries to JavaScript consumers, keep the JavaScript output, module exports, runtime dependencies, and public declarations aligned. The package should provide runnable JavaScript and, when useful, corresponding .d.ts files for TypeScript users.

9. Gradually Migrating JavaScript to TypeScript

A full migration is not always necessary or practical. Large applications may contain many JavaScript modules, tests, build scripts, and dependencies that cannot reasonably be converted together.

A gradual migration allows developers to introduce TypeScript in focused steps. Teams can start by enabling JavaScript support, adding JSDoc annotations to important files, checking existing JavaScript, and converting modules that benefit most from stronger type guarantees.

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "allowJs": true,
    "checkJs": true,
    "strict": true,
    "noEmit": true
  },
  "include": ["src/**/*"]
}

This is an illustrative starting point for a mixed JavaScript and TypeScript project. The noEmit setting is appropriate when another build tool handles output; remove or adjust it when the compiler itself must emit JavaScript.

A practical migration often begins with shared utilities, domain models, and service contracts because many parts of the application depend on them. Converting those modules can improve type information across multiple consumers.

Migration should also include testing and build validation. TypeScript can reveal existing problems, but merely changing a file extension does not guarantee that runtime behavior remains correct.

10. Module Compatibility Between JavaScript and TypeScript

JavaScript and TypeScript projects may use ECMAScript modules, CommonJS, or tools that support both formats. Interoperability depends on how modules are exported, how imports are resolved, and how the application is built and executed.

An ECMAScript module commonly uses export and import:

// utilities.js
export function greet(name) {
  return "Hello, " + name;
}

// app.ts
import { greet } from "./utilities.js";

console.log(greet("Asha"));

A CommonJS module instead commonly exposes values through module.exports or exports and consumes them through require():

// utilities.cjs
function greet(name) {
  return "Hello, " + name;
}

module.exports = { greet };

A mixed-format project should use the import syntax, file extensions, compiler options, and runtime loading behavior supported by its actual configuration. Options such as module, moduleResolution, esModuleInterop, and verbatimModuleSyntax can affect module processing or compatibility in specific setups.

Do not assume that every JavaScript package can be imported in the same way. Check the package's exports, module format, and TypeScript configuration before changing imports to work around a resolution error.

11. Common Interoperability Problems

Cannot find module or its declarations

Check the import path, file extension, installed package, module resolution configuration, and available declaration files. The correct fix depends on the project structure and module system.

JavaScript parameters have weak inferred types

Add JSDoc annotations or a declaration file when appropriate. These can improve type information without requiring the implementation to be immediately rewritten in TypeScript.

JavaScript consumers bypass TypeScript checks

TypeScript signatures do not enforce parameter types at runtime. Validate external or untrusted values when incorrect input could cause errors or compromise application behavior.

Module formats do not match

A CommonJS package and an ESM project may require different import handling. Check the package's declared entry points and the runtime and compiler settings before adjusting the code.

Generated JavaScript is missing at runtime

TypeScript source code may require compilation or bundling before execution. Verify the build output, deployment contents, and import paths used by the runtime.

Best Practices for JavaScript and TypeScript Interoperability

  • Reuse existing JavaScript modules when they already provide the required functionality.
  • Use allowJs when JavaScript files need to participate in a TypeScript project.
  • Enable checkJs selectively or project-wide when you are ready to address JavaScript type errors.
  • Use JSDoc annotations or declaration files to describe important JavaScript APIs.
  • Prefer accurate library declarations over declaring unknown modules as any.
  • Migrate high-value modules gradually instead of requiring an immediate full-project rewrite.
  • Align module formats, import paths, compiler options, and runtime behavior.
  • Test JavaScript consumers and validate external data when static TypeScript checks cannot protect the runtime boundary.

Conclusion

TypeScript and JavaScript interoperability allows developers to combine the flexibility of existing JavaScript code with the additional type safety available through TypeScript. Features such as allowJs, checkJs, JSDoc, declaration files, and compatible module configurations make this integration practical.

Whether you are maintaining an older JavaScript application, adopting a third-party package, or publishing a TypeScript library, focus on accurate type information, compatible module loading, and reliable runtime behavior. A gradual, well-tested approach makes it easier to improve a codebase without unnecessarily disrupting existing functionality.

Code Examples

Importing a JavaScript Utility into TypeScript

typescript
// formatter.js
export function formatCourseName(name) {
  return name.trim().toUpperCase();
}

// app.ts
import { formatCourseName } from "./formatter.js";

const result: string = formatCourseName("  TypeScript  ");

console.log(result);
    

TypeScript can reuse an existing JavaScript module. The quality of type checking depends on the information inferred from the JavaScript implementation or supplied by declarations and JSDoc.

Adding Types to JavaScript with JSDoc

javascript
/**
 * Adds two numbers.
 * @param {number} first
 * @param {number} second
 * @returns {number}
 */
export function add(first, second) {
  return first + second;
}

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

JSDoc annotations provide type information that TypeScript can use to check JavaScript files when the relevant checking options are enabled.

Creating a Declaration File

typescript
// math-utils.d.ts
export declare function add(
  first: number,
  second: number
): number;

// Corresponding implementation: math-utils.js
// export function add(first, second) {
//   return first + second;
// }

// A TypeScript consumer can import the function:
// import { add } from "./math-utils.js";
// console.log(add(10, 20));
    

A declaration file describes the public types of a JavaScript module without providing its runtime implementation. The JavaScript module must still be available when the application executes.

Using a Generic Type with Mixed Project Code

typescript
interface ApiResponse<T> {
  success: boolean;
  data: T;
}

// A JavaScript utility can return a compatible object.
function createResponse(data) {
  return {
    success: true,
    data
  };
}

const response: ApiResponse<string[]> = createResponse([
  "HTML",
  "CSS",
  "TypeScript"
]);

console.log(response.success);
console.log(response.data);
    

Shared TypeScript contracts can describe values produced by JavaScript utilities. TypeScript checks the declared assignment, but the static annotation is not runtime validation.

Gradual Migration Configuration

typescript
// Example tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "allowJs": true,
    "checkJs": true,
    "strict": true,
    "noEmit": true
  },
  "include": ["src/**/*"]
}
    

This configuration allows JavaScript and TypeScript files to participate in checking. The noEmit option is intended for setups where another build tool emits the application output; adjust it for projects that use tsc to generate JavaScript.

Pro Tip

Migrate JavaScript incrementally instead of rewriting an entire application at once. Enable allowJs, use checkJs and JSDoc to improve existing files, add declaration files when type information is missing, and verify module compatibility. Remember that TypeScript types do not validate values at runtime.

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.