Page Content

Tutorials

What is Definitely Typed in TypeScript?

Definitely Typed in TypeScript

The primary location for community-authored type definitions (also known as ambient declarations) for pre-existing JavaScript libraries is DefinitelyTyped (DT). It is frequently cited as one of TypeScript’s best features. DT’s goal is to make it possible for developers to utilise pre-existing JavaScript libraries in TypeScript in a secure and convenient manner.

Ambient declarations, which specify the form of external code without offering its implementation, allow TypeScript to be compatible with third-party JavaScript. The community has successfully gone ahead and described the nature of about 90% of the best JavaScript projects available, saving developers a great deal of work even though they can write their own declaration files (often with a .d.ts extension).

DT offers TypeScript developers several advantages:

  1. Safety and Code Intelligence: Even for code that was not initially written in TypeScript, type definitions provide strong code intelligence, including autocompletion, and improved compile-time safety. This implies that you can use these libraries interactively and exploratorily without having to access the documentation in a different window.
  2. Community Maintenance: One of the most active open-source (OSS) repositories on GitHub is DT. Developers can provide corrections to the repository if a library’s definition file (typings) is erroneous or lacking information.
  3. Migration Support: The process of converting current JavaScript projects to TypeScript is sped up by having well-maintained definitions.

Installing Types via NPM

NPM distributes type definitions under the @types scope that are kept in the DefinitelyTyped repository. The definition files required by the TypeScript compiler are automatically supplied by these packages.

The appropriate package @types/[package-name] must be installed via NPM in order to use the type definitions for a library with the name [package-name].

Example Installation for jQuery

Installing the type definitions for jquery is simple with NPM, as requested:

npm install @types/jquery --save-dev

Explanation of the command:

  • npm install @types/jquery: This installs the DefinitelyTyped community’s type definitions package for the jquery library.
  • --save-dev: Indicates that your package.json file should save this package as a development dependency. Type definitions are merely a developer tool because they are only present during build time and are removed from the output JavaScript code (a process known as Type Erasure). Types should typically be placed in devDependencies for isolated applications (such as server applications or web apps that aren’t published to NPM).

Global @types vs. Module @types

Module types and global types are the two main methods of consuming type definitions that are supported by the @types mechanism.

Module @types (Recommended Approach)

Using the common ES module import syntax (import/export), the module approach merges types. It is generally advised to use this method, especially for frameworks such as jQuery.

TypeScript resolves the types automatically when the corresponding module is imported once a type definition is installed. Usually, no particular setup is needed.

Code Example: Using Module @types for jQuery

Assuming you have installed the jquery library and its types (npm install jquery @types/jquery):

// file: module-usage.ts

// Import jQuery using ES module syntax
import * as $ from "jquery";

// Use $ within the scope of this module
$('#my-button').click(function() {
    $(this).hide();
});

// A type-safe call that utilizes jQuery's module definition
$('div.content').fadeIn(500); 

Output:

When compiled (e.g., using tsc with module: commonjs), the resulting JavaScript file will handle the runtime import/require logic defined by jQuery as a module, while TypeScript provides full type safety and autocompletion for the $() function and its methods (like .click() and .fadeIn()) during development.

Global @types (Automatic Inclusion)

The functionality of many classic JavaScript libraries is exposed globally (for example, Node.js exposes process, or jQuery exposes $ globally). These libraries’ type definitions frequently include ambient declarations that, when included in the compilation context, enable global usage.

Any installed @types declaration that allows global consumption is automatically added to the global namespace of your project by default.

Code Example: Using Global @types for jQuery

If a file does not contain any import or export statements, TypeScript treats it as being in the global namespace (script mode).

Assuming @types/jquery is installed, in a script file without imports:

// file: global-script.ts (No imports/exports)

// $ is available globally without requiring an explicit import
$('.app-container').show();

// TypeScript ensures type safety on the globally declared $
// Example: Attempting to call .show() with an invalid argument (inferring general TS behavior)
// $('body').show(1, 2, 3); // <-- TypeScript would throw an error if this signature was wrong

Output:

The TypeScript compiler assumes the global variable $ exists at runtime, thanks to the declaration file from @types/jquery, allowing the code to be type-checked.

Controlling Global Leak-in with

In large teams or when combining multiple environments (such as browser and Node.js code), the automatic inclusion of global types can occasionally result in disputes or pollution of the global namespace. Globals like process, for instance, may “leak” into your client-side code if you install @types/node, deceiving the type checker.

With TypeScript, you can use the types option in your tsconfig.json file to specify which packages’ global definitions are included.

The types array in compilerOptions forces you to explicitly list every package whose globals you wish to disclose, switching from automatic discovery of all global types to an opt-in process.

Code Example: Controlling Global Inclusion via tsconfig.json

To explicitly allow only jQuery globals:

// tsconfig.json excerpt
{
  "compilerOptions": {
    "types": [
      "jquery"
    ]
  }
}

Scenario and Output/Result:

  1. Installation: Suppose that you install the jQuery and Node.js types.
  2. Configuration: Just "jquery" is listed in the tsconfig.json file mentioned earlier.
  3. Code Check:
    • jQuery Global ($): Will be allowed globally in your code, as it is listed in the types array.
    • Node Global (process): Will not be available globally. Even though @types/node is installed, its globals (e.g., process) will not leak into your code until you add "node" to the types option in tsconfig.json.

A TypeScript error message like "cannot find name 'process'" is likely to appear if you attempt to access the process global in a file without an explicit import (and only jquery is listed in types). By removing potential conflicts and ensuring that only the required global type definitions are available in the global scope of your project, this method enhances type accuracy.

Index