matijao/webdev huggingface dataset:
TypeScript: Documentation - Templates

Templates

global-modifying-module.d.ts

global-plugin.d.ts
global.d.ts
module-class.d.ts
module-function.d.ts
module-plugin.d.ts
module.d.ts
On this page
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
1+

Last updated: Nov 27, 2023

This page loaded in 9.111 seconds.
TypeScript: Documentation - Modules - Introduction

Modules - Introduction

This document is divided into four sections:

The first section develops the theory behind how TypeScript approaches modules. If you want to be able to write the correct module-related compiler options for any situation, reason about how to integrate TypeScript with other tools, or understand how TypeScript processes dependency packages, this is the place to start. While there are guides and reference pages on these topics, building an understanding of these fundamentals will make reading the guides easier, and give you a mental framework for dealing with real-world problems not specifically covered here.
The guides show how to accomplish specific real-world tasks, starting with picking the right compilation settings for a new project. The guides are a good place to start both for beginners who want to get up and running as quickly as possible and for experts who already have a good grasp of the theory but want concrete guidance on a complicated task.
The reference section provides a more detailed look at the syntaxes and configurations presented in previous sections.
The appendices cover complicated topics that deserve additional explanation in more detail than the theory or reference sections allow.
On this page
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

AB

Last updated: Nov 27, 2023

This page loaded in 2.105 seconds.
TypeScript: Documentation - Nightly Builds

Nightly Builds

A nightly build from the TypeScript’s main branch is published by midnight PST to npm. Here is how you can get it and use it with your tools.

Using npm
npm install -D typescript@next
Updating your IDE to use the nightly builds

You can also update your editor/IDE to use the nightly drop. You will typically need to install the package through npm. The rest of this section mostly assumes typescript@next is already installed.

Visual Studio Code

The VS Code website has documentation on selecting a workspace version of TypeScript. After installing a nightly version of TypeScript in your workspace, you can follow directions there, or simply update your workspace settings in the JSON view. A direct way to do this is to open or create your workspace’s .vscode/settings.json and add the following property:

"typescript.tsdk": "<path to your folder>/node_modules/typescript/lib"

Alternatively, if you simply want to run the nightly editing experience for JavaScript and TypeScript in Visual Studio Code without changing your workspace version, you can run the JavaScript and TypeScript Nightly Extension

Sublime Text

Update the Settings - User file with the following:

"typescript_tsdk": "<path to your folder>/node_modules/typescript/lib"

More information is available at the TypeScript Plugin for Sublime Text installation documentation.

Visual Studio 2013 and 2015

Note: Most changes do not require you to install a new version of the VS TypeScript plugin.

The nightly build currently does not include the full plugin setup, but we are working on publishing an installer on a nightly basis as well.

Download the VSDevMode.ps1 script.

Also see our wiki page on using a custom language service file.

From a PowerShell command window, run:

For VS 2015:

VSDevMode.ps1 14 -tsScript <path to your folder>/node_modules/typescript/lib

For VS 2013:

VSDevMode.ps1 12 -tsScript <path to your folder>/node_modules/typescript/lib
IntelliJ IDEA (Mac)

Go to Preferences > Languages & Frameworks > TypeScript:

TypeScript Version: If you installed with npm: /usr/local/lib/node_modules/typescript/lib

IntelliJ IDEA (Windows)

Go to File > Settings > Languages & Frameworks > TypeScript:

TypeScript Version: If you installed with npm: C:\Users\USERNAME\AppData\Roaming\npm\node_modules\typescript\lib

On this page
Using npm
Updating your IDE to use the nightly builds
Visual Studio Code
Sublime Text
Visual Studio 2013 and 2015
IntelliJ IDEA (Mac)
IntelliJ IDEA (Windows)
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
S
DR
NS
4+

Last updated: Nov 27, 2023

This page loaded in 1.377 seconds.
TypeScript: Documentation - Consumption

Consumption
Downloading

Getting type declarations requires no tools apart from npm.

As an example, getting the declarations for a library like lodash takes nothing more than the following command

npm install --save-dev @types/lodash

It is worth noting that if the npm package already includes its declaration file as described in Publishing, downloading the corresponding @types package is not needed.

Consuming

From there you’ll be able to use lodash in your TypeScript code with no fuss. This works for both modules and global code.

For example, once you’ve npm install-ed your type declarations, you can use imports and write

import * as _ from "lodash";
_.padStart("Hello TypeScript!", 20, " ");

or if you’re not using modules, you can just use the global variable _.

_.padStart("Hello TypeScript!", 20, " ");
Searching

For the most part, type declaration packages should always have the same name as the package name on npm, but prefixed with @types/, but if you need, you can use the Yarn package search to find the package for your favorite library.

Note: if the declaration file you are searching for is not present, you can always contribute one back and help out the next developer looking for it. Please see the DefinitelyTyped contribution guidelines page for details.

On this page
Downloading
Consuming
Searching
Is this page helpful?
Yes
No
Previous
Publishing

How to get your d.ts files to users

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
IO
KO
EB
5+

Last updated: Nov 27, 2023

This page loaded in 0.475 seconds.
TypeScript: Documentation - JS Projects Utilizing TypeScript

JS Projects Utilizing TypeScript

The type system in TypeScript has different levels of strictness when working with a codebase:

A type-system based only on inference with JavaScript code
Incremental typing in JavaScript via JSDoc
Using // @ts-check in a JavaScript file
TypeScript code
TypeScript with strict enabled

Each step represents a move towards a safer type-system, but not every project needs that level of verification.

TypeScript with JavaScript

This is when you use an editor which uses TypeScript to provide tooling like auto-complete, jump to symbol and refactoring tools like rename. The homepage has a list of editors which have TypeScript plugins.

Providing Type Hints in JS via JSDoc

In a .js file, types can often be inferred. When types can’t be inferred, they can be specified using JSDoc syntax.

JSDoc annotations come before a declaration will be used to set the type of that declaration. For example:

/** @type {number} */
var x;
 
x = 0; // OK
x = false; // OK?!
Try

You can find the full list of supported JSDoc patterns in JSDoc Supported Types.

@ts-check

The last line of the previous code sample would raise an error in TypeScript, but it doesn’t by default in a JS project. To enable errors in your JavaScript files add: // @ts-check to the first line in your .js files to have TypeScript raise it as an error.

// @ts-check
/** @type {number} */
var x;
 
x = 0; // OK
x = false; // Not OK
Type 'boolean' is not assignable to type 'number'.
Type 'boolean' is not assignable to type 'number'.
Try

If you have a lot of JavaScript files you want to add errors to then you can switch to using a jsconfig.json. You can skip checking some files by adding a // @ts-nocheck comment to files.

TypeScript may offer you errors which you disagree with, in those cases you can ignore errors on specific lines by adding // @ts-ignore or // @ts-expect-error on the preceding line.

// @ts-check
/** @type {number} */
var x;
 
x = 0; // OK
// @ts-expect-error
x = false; // Not OK
Try

To learn more about how JavaScript is interpreted by TypeScript read How TS Type Checks JS

On this page
TypeScript with JavaScript
Providing Type Hints in JS via JSDoc
@ts-check
Is this page helpful?
Yes
No
Next
Type Checking JavaScript Files

How to add type checking to JavaScript files using TypeScript

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

OT

Last updated: Nov 27, 2023
TypeScript: Documentation - Module: Class

Module: Class

For example, when you want to work with JavaScript code which looks like:

const Greeter = require("super-greeter");
const greeter = new Greeter();
greeter.greet();

To handle both importing via UMD and modules:

// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ This is the module template file for class modules.
 *~ You should rename it to index.d.ts and place it in a folder with the same name as the module.
 *~ For example, if you were writing a file for "super-greeter", this
 *~ file should be 'super-greeter/index.d.ts'
 */
// Note that ES6 modules cannot directly export class objects.
// This file should be imported using the CommonJS-style:
//   import x = require('[~THE MODULE~]');
//
// Alternatively, if --allowSyntheticDefaultImports or
// --esModuleInterop is turned on, this file can also be
// imported as a default import:
//   import x from '[~THE MODULE~]';
//
// Refer to the TypeScript documentation at
// https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
// to understand common workarounds for this limitation of ES6 modules.
/*~ If this module is a UMD module that exposes a global variable 'myClassLib' when
 *~ loaded outside a module loader environment, declare that global here.
 *~ Otherwise, delete this declaration.
 */
export as namespace "super-greeter";
/*~ This declaration specifies that the class constructor function
 *~ is the exported object from the file
 */
export = Greeter;
/*~ Write your module's methods and properties in this class */
declare class Greeter {
  constructor(customGreeting?: string);
  greet: void;
  myMethod(opts: MyClass.MyClassMethodOptions): number;
}
/*~ If you want to expose types from your module as well, you can
 *~ place them in this block.
 *~
 *~ Note that if you decide to include this namespace, the module can be
 *~ incorrectly imported as a namespace object, unless
 *~ --esModuleInterop is turned on:
 *~   import * as x from '[~THE MODULE~]'; // WRONG! DO NOT DO THIS!
 */
declare namespace MyClass {
  export interface MyClassMethodOptions {
    width?: number;
    height?: number;
  }
}
On this page
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
AC
DR
2+

Last updated: Nov 27, 2023

This page loaded in 1.315 seconds.
TypeScript: Documentation - Global: Modifying Module

Global: Modifying Module
Global-modifying Modules

A global-modifying module alters existing values in the global scope when they are imported. For example, there might exist a library which adds new members to String.prototype when imported. This pattern is somewhat dangerous due to the possibility of runtime conflicts, but we can still write a declaration file for it.

Identifying global-modifying modules

Global-modifying modules are generally easy to identify from their documentation. In general, they’re similar to global plugins, but need a require call to activate their effects.

You might see documentation like this:

// 'require' call that doesn't use its return value
var unused = require("magic-string-time");
/* or */
require("magic-string-time");
var x = "hello, world";
// Creates new methods on built-in types
console.log(x.startsWithHello());
var y = [1, 2, 3];
// Creates new methods on built-in types
console.log(y.reverseAndSort());

Here is an example

// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ This is the global-modifying module template file. You should rename it to index.d.ts
 *~ and place it in a folder with the same name as the module.
 *~ For example, if you were writing a file for "super-greeter", this
 *~ file should be 'super-greeter/index.d.ts'
 */
/*~ Note: If your global-modifying module is callable or constructable, you'll
 *~ need to combine the patterns here with those in the module-class or module-function
 *~ template files
 */
declare global {
  /*~ Here, declare things that go in the global namespace, or augment
   *~ existing declarations in the global namespace
   */
  interface String {
    fancyFormat(opts: StringFormatOptions): string;
  }
}
/*~ If your module exports types or values, write them as usual */
export interface StringFormatOptions {
  fancinessLevel: number;
}
/*~ For example, declaring a method on the module (in addition to its global side effects) */
export function doSomething(): void;
/*~ If your module exports nothing, you'll need this line. Otherwise, delete it */
export {};
On this page
Global-modifying Modules
Identifying global-modifying modules
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
1+

Last updated: Nov 27, 2023

This page loaded in 1.208 seconds.
TypeScript: Documentation - Module: Plugin

Module: Plugin

For example, when you want to work with JavaScript code which extends another library.

import { greeter } from "super-greeter";
// Normal Greeter API
greeter(2);
greeter("Hello world");
// Now we extend the object with a new function at runtime
import "hyper-super-greeter";
greeter.hyperGreet();

The definition for “super-greeter”:

/*~ This example shows how to have multiple overloads for your function */
export interface GreeterFunction {
  (name: string): void
  (time: number): void
}
/*~ This example shows how to export a function specified by an interface */
export const greeter: GreeterFunction;

We can extend the existing module like the following:

// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ This is the module plugin template file. You should rename it to index.d.ts
 *~ and place it in a folder with the same name as the module.
 *~ For example, if you were writing a file for "super-greeter", this
 *~ file should be 'super-greeter/index.d.ts'
 */
/*~ On this line, import the module which this module adds to */
import { greeter } from "super-greeter";
/*~ Here, declare the same module as the one you imported above
 *~ then we expand the existing declaration of the greeter function
 */
export module "super-greeter" {
  export interface GreeterFunction {
    /** Greets even better! */
    hyperGreet(): void;
  }
}

This uses declaration merging

The Impact of ES6 on Module Plugins

Some plugins add or modify top-level exports on existing modules. While this is legal in CommonJS and other loaders, ES6 modules are considered immutable and this pattern will not be possible. Because TypeScript is loader-agnostic, there is no compile-time enforcement of this policy, but developers intending to transition to an ES6 module loader should be aware of this.

On this page
The Impact of ES6 on Module Plugins
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
B
1+

Last updated: Nov 27, 2023

This page loaded in 0.462 seconds.
TypeScript: Documentation - Module: Function

Module: Function

For example, when you want to work with JavaScript code which looks like:

import greeter from "super-greeter";
greeter(2);
greeter("Hello world");

To handle both importing via UMD and modules:

// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ This is the module template file for function modules.
 *~ You should rename it to index.d.ts and place it in a folder with the same name as the module.
 *~ For example, if you were writing a file for "super-greeter", this
 *~ file should be 'super-greeter/index.d.ts'
 */
// Note that ES6 modules cannot directly export class objects.
// This file should be imported using the CommonJS-style:
//   import x = require('[~THE MODULE~]');
//
// Alternatively, if --allowSyntheticDefaultImports or
// --esModuleInterop is turned on, this file can also be
// imported as a default import:
//   import x from '[~THE MODULE~]';
//
// Refer to the TypeScript documentation at
// https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
// to understand common workarounds for this limitation of ES6 modules.
/*~ If this module is a UMD module that exposes a global variable 'myFuncLib' when
 *~ loaded outside a module loader environment, declare that global here.
 *~ Otherwise, delete this declaration.
 */
export as namespace myFuncLib;
/*~ This declaration specifies that the function
 *~ is the exported object from the file
 */
export = Greeter;
/*~ This example shows how to have multiple overloads for your function */
declare function Greeter(name: string): Greeter.NamedReturnType;
declare function Greeter(length: number): Greeter.LengthReturnType;
/*~ If you want to expose types from your module as well, you can
 *~ place them in this block. Often you will want to describe the
 *~ shape of the return type of the function; that type should
 *~ be declared in here, as this example shows.
 *~
 *~ Note that if you decide to include this namespace, the module can be
 *~ incorrectly imported as a namespace object, unless
 *~ --esModuleInterop is turned on:
 *~   import * as x from '[~THE MODULE~]'; // WRONG! DO NOT DO THIS!
 */
declare namespace Greeter {
  export interface LengthReturnType {
    width: number;
    height: number;
  }
  export interface NamedReturnType {
    firstName: string;
    lastName: string;
  }
  /*~ If the module also has properties, declare them here. For example,
   *~ this declaration says that this code is legal:
   *~   import f = require('super-greeter');
   *~   console.log(f.defaultName);
   */
  export const defaultName: string;
  export let defaultLength: number;
}
On this page
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
DR
2+

Last updated: Nov 27, 2023

This page loaded in 0.916 seconds.
TypeScript: Documentation - Introduction

Introduction

The Declaration Files section is designed to teach you how to write a high-quality TypeScript Declaration File. We need to assume basic familiarity with the TypeScript language in order to get started.

If you haven’t already, you should read the TypeScript Handbook to familiarize yourself with basic concepts, especially types and modules.

The most common case for learning how .d.ts files work is that you’re typing an npm package with no types. In that case, you can jump straight to Modules .d.ts.

The Declaration Files section is broken down into the following sections.

Declaration Reference

We are often faced with writing a declaration file when we only have examples of the underlying library to guide us. The Declaration Reference section shows many common API patterns and how to write declarations for each of them. This guide is aimed at the TypeScript novice who may not yet be familiar with every language construct in TypeScript.

Library Structures

The Library Structures guide helps you understand common library formats and how to write a proper declaration file for each format. If you’re editing an existing file, you probably don’t need to read this section. Authors of new declaration files are strongly encouraged to read this section to properly understand how the format of the library influences the writing of the declaration file.

In the Template section you’ll find a number of declaration files that serve as a useful starting point when writing a new file. If you already know what your structure is, see the d.ts Template section in the sidebar.

Do’s and Don’ts

Many common mistakes in declaration files can be easily avoided. The Do’s and Don’ts section identifies common errors, describes how to detect them, and how to fix them. Everyone should read this section to help themselves avoid common mistakes.

Deep Dive

For seasoned authors interested in the underlying mechanics of how declaration files work, the Deep Dive section explains many advanced concepts in declaration writing, and shows how to leverage these concepts to create cleaner and more intuitive declaration files.

Publish to npm

The Publishing section explains how to publish your declaration files to an npm package, and shows how to manage your dependent packages.

Find and Install Declaration Files

For JavaScript library users, the Consumption section offers a few simple steps to locate and install corresponding declaration files.

On this page
Declaration Reference
Library Structures
Do’s and Don’ts
Deep Dive
Publish to npm
Find and Install Declaration Files
Is this page helpful?
Yes
No
Next
Declaration Reference

How to create a d.ts file for a module

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
JW
NR
DK
11+

Last updated: Nov 27, 2023

This page loaded in 3.344 seconds.
TypeScript: Documentation - TypeScript 1.3

TypeScript 1.3
Protected

The new protected modifier in classes works like it does in familiar languages like C++, C#, and Java. A protected member of a class is visible only inside subclasses of the class in which it is declared:

class Thing {
  protected doSomething() {
    /* ... */
  }
}
class MyThing extends Thing {
  public myMethod() {
    // OK, can access protected member from subclass
    this.doSomething();
  }
}
var t = new MyThing();
t.doSomething(); // Error, cannot call protected member from outside class
Tuple types

Tuple types express an array where the type of certain elements is known, but need not be the same. For example, you may want to represent an array with a string at position 0 and a number at position 1:

// Declare a tuple type
var x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error

When accessing an element with a known index, the correct type is retrieved:

console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

Note that in TypeScript 1.4, when accessing an element outside the set of known indices, a union type is used instead:

x[3] = "world"; // OK
console.log(x[5].toString()); // OK, 'string' and 'number' both have toString
x[6] = true; // Error, boolean isn't number or string
On this page
Protected
Tuple types
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
2+

Last updated: Nov 27, 2023

This page loaded in 3.901 seconds.
TypeScript: Documentation - TypeScript 1.1

TypeScript 1.1
Performance Improvements

The 1.1 compiler is typically around 4x faster than any previous release. See this blog post for some impressive charts.

Better Module Visibility Rules

TypeScript now only strictly enforces the visibility of types in modules if the declaration flag is provided. This is very useful for Angular scenarios, for example:

module MyControllers {
  interface ZooScope extends ng.IScope {
    animals: Animal[];
  }
  export class ZooController {
    // Used to be an error (cannot expose ZooScope), but now is only
    // an error when trying to generate .d.ts files
    constructor(public $scope: ZooScope) {}
    /* more code */
  }
}
On this page
Performance Improvements
Better Module Visibility Rules
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
MHK
JB
2+

Last updated: Nov 27, 2023

This page loaded in 3.489 seconds.
TypeScript: Documentation - TypeScript 2.5

TypeScript 2.5
Optional 
catch
 clause variables

Thanks to work done by @tinganho, TypeScript 2.5 implements a new ECMAScript feature that allows users to omit the variable in catch clauses. For example, when using JSON.parse you may need to wrap calls to the function with a try/catch, but you may not end up using the SyntaxError that gets thrown when input is erroneous.

let input = "...";
try {
  JSON.parse(input);
} catch {
  // ^ Notice that our `catch` clause doesn't declare a variable.
  console.log("Invalid JSON given\n\n" + input);
}
Type assertion/cast syntax in 
checkJs
/
@ts-check
 mode

TypeScript 2.5 introduces the ability to assert the type of expressions when using plain JavaScript in your projects. The syntax is an /** @type {...} */ annotation comment followed by a parenthesized expression whose type needs to be re-evaluated. For example:

var x = /** @type {SomeType} */ AnyParenthesizedExpression;
Deduplicated and redirected packages

When importing using the Node module resolution strategy in TypeScript 2.5, the compiler will now check whether files originate from “identical” packages. If a file originates from a package with a package.json containing the same name and version fields as a previously encountered package, then TypeScript will redirect itself to the top-most package. This helps resolve problems where two packages might contain identical declarations of classes, but which contain private members that cause them to be structurally incompatible.

As a nice bonus, this can also reduce the memory and runtime footprint of the compiler and language service by avoiding loading .d.ts files from duplicate packages.

The 
--preserveSymlinks
 compiler flag

TypeScript 2.5 brings the preserveSymlinks flag, which parallels the behavior of the --preserve-symlinks flag in Node.js. This flag also exhibits the opposite behavior to Webpack’s resolve.symlinks option (i.e. setting TypeScript’s preserveSymlinks to true parallels setting Webpack’s resolve.symlinks to false, and vice-versa).

In this mode, references to modules and packages (e.g. imports and /// <reference type="..." /> directives) are all resolved relative to the location of the symbolic link file, rather than relative to the path that the symbolic link resolves to. For a more concrete example, we’ll defer to the documentation on the Node.js website.

On this page
Optional catch clause variables
Type assertion/cast syntax in checkJs/@ts-check mode
Deduplicated and redirected packages
The --preserveSymlinks compiler flag
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

MH
OT
JB
2+

Last updated: Nov 27, 2023
TypeScript: Documentation - TypeScript 3.1

TypeScript 3.1
Mapped types on tuples and arrays

In TypeScript 3.1, mapped object types[1] over tuples and arrays now produce new tuples/arrays, rather than creating a new type where members like push(), pop(), and length are converted. For example:

type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> };
type Coordinate = [number, number];
type PromiseCoordinate = MapToPromise<Coordinate>; // [Promise<number>, Promise<number>]

MapToPromise takes a type T, and when that type is a tuple like Coordinate, only the numeric properties are converted. In [number, number], there are two numerically named properties: 0 and 1. When given a tuple like that, MapToPromise will create a new tuple where the 0 and 1 properties are Promises of the original type. So the resulting type PromiseCoordinate ends up with the type [Promise<number>, Promise<number>].

Properties declarations on functions

TypeScript 3.1 brings the ability to define properties on function declarations and const-declared functions, simply by assigning to properties on these functions in the same scope. This allows us to write canonical JavaScript code without resorting to namespace hacks. For example:

function readImage(path: string, callback: (err: any, image: Image) => void) {
  // ...
}
readImage.sync = (path: string) => {
  const contents = fs.readFileSync(path);
  return decodeImageSync(contents);
};

Here, we have a function readImage which reads an image in a non-blocking asynchronous way. In addition to readImage, we’ve provided a convenience function on readImage itself called readImage.sync.

While ECMAScript exports are often a better way of providing this functionality, this new support allows code written in this style to “just work” in TypeScript. Additionally, this approach for property declarations allows us to express common patterns like defaultProps and propTypes on React function components (formerly known as SFCs).

export const FooComponent = ({ name }) => <div>Hello! I am {name}</div>;
FooComponent.defaultProps = {
  name: "(anonymous)",
};

[1] More specifically, homomorphic mapped types like in the above form.

Version selection with 
typesVersions

Feedback from our community, as well as our own experience, has shown us that leveraging the newest TypeScript features while also accommodating users on the older versions are difficult. TypeScript introduces a new feature called typesVersions to help accommodate these scenarios.

You can read about it in the Publishing section of the declaration files section

On this page
Mapped types on tuples and arrays
Properties declarations on functions
Version selection with typesVersions
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

DR
OT
CF
MU
SS
10+

Last updated: Nov 27, 2023

This page loaded in 0.279 seconds.
TypeScript: Documentation - Using Babel with TypeScript

Using Babel with TypeScript
Babel vs 
tsc
 for TypeScript

When making a modern JavaScript project, you might ask yourself what is the right way to convert files from TypeScript to JavaScript?

A lot of the time the answer is “it depends”, or “someone may have decided for you” depending on the project. If you are building your project with an existing framework like tsdx, Angular, NestJS or any framework mentioned in the Getting Started then this decision is handled for you.

However, a useful heuristic could be:

Is your build output mostly the same as your source input files? Use tsc
Do you need a build pipeline with multiple potential outputs? Use babel for transpiling and tsc for type checking
Babel for transpiling, 
tsc
 for types

This is a common pattern for projects with existing build infrastructure which may have been ported from a JavaScript codebase to TypeScript.

This technique is a hybrid approach, using Babel’s preset-typescript to generate your JS files, and then using TypeScript to do type checking and .d.ts file generation.

By using babel’s support for TypeScript, you get the ability to work with existing build pipelines and are more likely to have a faster JS emit time because Babel does not type check your code.

Type Checking and d.ts file generation

The downside to using babel is that you don’t get type checking during the transition from TS to JS. This can mean that type errors which you miss in your editor could sneak through into production code.

In addition to that, Babel cannot create .d.ts files for your TypeScript which can make it harder to work with your project if it is a library.

To fix these issues, you would probably want to set up a command to type check your project using TSC. This likely means duplicating some of your babel config into a corresponding tsconfig.json and ensuring these flags are enabled:

"compilerOptions": {
  // Ensure that .d.ts files are created by tsc, but not .js files
  "declaration": true,
  "emitDeclarationOnly": true,
  // Ensure that Babel can safely transpile files in the TypeScript project
  "isolatedModules": true
}

For more information on these flags:

isolatedModules
declaration, emitDeclarationOnly
On this page
Babel vs tsc for TypeScript
Babel for transpiling, tsc for types
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

OT
R
US

Last updated: Nov 27, 2023

This page loaded in 0.265 seconds.
TypeScript: Documentation - Modules - Introduction

Modules - Introduction

This document is divided into four sections:

The first section develops the theory behind how TypeScript approaches modules. If you want to be able to write the correct module-related compiler options for any situation, reason about how to integrate TypeScript with other tools, or understand how TypeScript processes dependency packages, this is the place to start. While there are guides and reference pages on these topics, building an understanding of these fundamentals will make reading the guides easier, and give you a mental framework for dealing with real-world problems not specifically covered here.
The guides show how to accomplish specific real-world tasks, starting with picking the right compilation settings for a new project. The guides are a good place to start both for beginners who want to get up and running as quickly as possible and for experts who already have a good grasp of the theory but want concrete guidance on a complicated task.
The reference section provides a more detailed look at the syntaxes and configurations presented in previous sections.
The appendices cover complicated topics that deserve additional explanation in more detail than the theory or reference sections allow.
On this page
Is this page helpful?
Yes
No

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Contributors to this page:

AB

Last updated: Nov 27, 2023

This page loaded in 0.253 seconds.