### Example Import List
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html
An example of an import list that might be sorted differently based on case sensitivity.
```ts
import {
Toggle,
freeze,
toBoolean,
} from "./utils";
```
--------------------------------
### Install tslib utility library
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
Install the `tslib` package using npm to manage helper functions.
```sh
npm install tslib
```
--------------------------------
### Example Composite Project Structure
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-7.html
Illustrates a typical monorepo structure where multiple packages are referenced by a main application project. This setup is common for managing dependencies and code sharing.
```plaintext
packages
├── graphics/
│ ├── tsconfig.json
│ └── src/
│ └── ...
├── sound/
│ ├── tsconfig.json
│ └── src/
│ └── ...
├── networking/
│ ├── tsconfig.json
│ └── src/
│ └── ...
├── input/
│ ├── tsconfig.json
│ └── src/
│ └── ...
└── app/
├── tsconfig.json
├── some-script.js
└── src/
└── ...
```
--------------------------------
### Install Nightly TypeScript Build
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-6.html
Use this command to install the latest nightly build of TypeScript.
```bash
npm install -g typescript@next
```
--------------------------------
### Importing Modules Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
Demonstrates how different modules within a library can be imported using the require function.
```javascript
var a = require("myLib");
var b = require("myLib/foo");
var c = require("myLib/bar");
var d = require("myLib/bar/baz");
```
--------------------------------
### tsconfig.json Configuration Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-5.html
An example of a tsconfig.json file, which specifies the root files and compiler options required to compile a TypeScript project.
```json
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"sourceMap": true
}
}
```
--------------------------------
### Install Type Declarations with npm
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html
Use npm to install type declaration packages for libraries. This is typically done as a development dependency.
```cmd
npm install --save-dev @types/lodash
```
--------------------------------
### Library File Layout Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
Illustrates how the directory structure of a library corresponds to the structure of its declaration files.
```plaintext
myLib
+---- index.js
+---- foo.js
+---- bar
+---- index.js
+---- baz.js
```
--------------------------------
### Importing Modules with '#root/' Prefix
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-6-0.html
Example of importing a module using the '#root/' subpath alias.
```js
import * as utils from "#root/utils.js";
```
--------------------------------
### Original Code for Import Management Examples
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html
This is the initial state of the code used to demonstrate import management features.
```typescript
import {
Zebra,
Moose,
HoneyBadger,
} from "./zoo";
import { foo, bar } from "./helper";
let x: Moose | HoneyBadger = foo();
```
--------------------------------
### Dependency Chain Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html
Illustrates a typical dependency chain where changes in one file can affect subsequent files. This example helps visualize the impact of the `assumeChangesOnlyAffectDirectDependencies` option.
```plaintext
fileA.ts <- fileB.ts <- fileC.ts <- fileD.ts
```
--------------------------------
### Vue.js Component with `
```
--------------------------------
### Using 'module-function.d.ts' template
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-plugin-d-ts.html
Example demonstrating a module that is intended to be called directly after being imported, suitable for the 'module-function.d.ts' template.
```javascript
var x = require("foo");
// Note: calling 'x' as a function
var y = x(42);
```
--------------------------------
### Async Function Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
An example of an async function that uses await with a delay. This can be downleveled to ES3/ES5.
```typescript
function delay(milliseconds: number) {
return new Promise(resolve => {
setTimeout(resolve, milliseconds);
});
}
async function dramaticWelcome() {
console.log("Hello");
for (let i = 0; i < 3; i++) {
await delay(500);
console.log(".");
}
console.log("World!");
}
dramaticWelcome();
```
--------------------------------
### Type Annotation Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-3.html
Demonstrates how a type annotation is used in TypeScript.
```typescript
export let p: Person
```
--------------------------------
### Basic Usage of --explainFiles
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html
Run the TypeScript compiler with the `--explainFiles` flag to get detailed output about file inclusion.
```sh
tsc --explainFiles
```
--------------------------------
### Organize Imports Command Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html
Demonstrates the result of the 'Organize Imports' command, which removes unused imports and sorts the remaining ones.
```typescript
import { foo } from "./helper";
import { HoneyBadger, Moose } from "./zoo";
let x: Moose | HoneyBadger = foo();
```
--------------------------------
### Using 'module-class.d.ts' template
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-plugin-d-ts.html
Example demonstrating a module that is intended to be instantiated using the 'new' operator, suitable for the 'module-class.d.ts' template.
```javascript
var x = require("bar");
// Note: using 'new' operator on the imported variable
var y = new x("hello");
```
--------------------------------
### Module Resolution Examples for node16/nodenext
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
Illustrates how TypeScript resolves module specifiers under `node16` and `nodenext` modes, differentiating between ECMAScript and CommonJS formats and their impact on emitted JavaScript. Shows examples using `.mts` and `.cts` files.
```typescript
// @Filename: module.mts
import x from "./mod.js"; // `import` algorithm due to file format (emitted as-written)
import("./mod.js"); // `import` algorithm due to syntax (emitted as-written)
type Mod = typeof import("./mod.js"); // `import` algorithm due to file format
import mod = require("./mod"); // `require` algorithm due to syntax (emitted as `require`)
// @Filename: commonjs.cts
import x from "./mod"; // `require` algorithm due to file format (emitted as `require`)
import("./mod.js"); // `import` algorithm due to syntax (emitted as-written)
type Mod = typeof import("./mod"); // `require` algorithm due to file format
import mod = require("./mod"); // `require` algorithm due to syntax (emitted as `require`)
```
--------------------------------
### Basic Assertion Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
Demonstrates the basic usage of an assertion function like Node.js's `assert`. If the condition is false, an `AssertionError` is thrown.
```js
assert(someValue === 42);
```
--------------------------------
### TypeScript Mixin Class Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
Demonstrates the mixin class pattern in TypeScript, showing how to create a `Tagged` class factory that can be applied to other classes. This example illustrates extending base classes with additional properties and methods.
```typescript
class Point {
constructor(public x: number, public y: number) {}
}
class Person {
constructor(public name: string) {}
}
type Constructor = new (...args: any[]) => T;
function Tagged>(Base: T) {
return class extends Base {
_tag: string;
constructor(...args: any[]) {
super(...args);
this._tag = "";
}
};
}
const TaggedPoint = Tagged(Point);
let point = new TaggedPoint(10, 20);
point._tag = "hello";
class Customer extends Tagged(Person) {
accountBalance: number;
}
let customer = new Customer("Joe");
customer._tag = "test";
customer.accountBalance = 0;
```
--------------------------------
### Example of Global Plugin Usage
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-plugin-d-ts.html
Demonstrates how global plugins add new methods to built-in types like String and Array.
```js
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());
```
--------------------------------
### Awaited Type Examples
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html
Demonstrates the usage of the Awaited utility type with Promises and other types.
```typescript
// A = string
type A = Awaited>;
// B = number
type B = Awaited>>;
// C = boolean | number
type C = Awaited>;
```
--------------------------------
### Importing a Class Module in JavaScript
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-class-d-ts.html
Example of how to import and instantiate a class from a JavaScript module using CommonJS.
```javascript
const Greeter = require("super-greeter");
const greeter = new Greeter();
greeter.greet();
```
--------------------------------
### Strict Class Initialization Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html
Demonstrates the `strictPropertyInitialization` check. Properties must be initialized in the constructor or via an initializer, otherwise an error is reported.
```typescript
class C {
foo: number;
bar = "hello";
baz: boolean;
// ~~~
// Error! Property 'baz' has no initializer and is not definitely assigned in the
// constructor.
constructor() {
this.foo = 42;
}
}
```
--------------------------------
### Using BasicCalculator Fluent API
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-7.html
Example of how to use the fluent API provided by `BasicCalculator` to chain methods for a concise expression.
```typescript
import calc from "./BasicCalculator";
let v = new calc(2).multiply(5).add(1).currentValue();
```
--------------------------------
### Example of a Global Library Usage (jQuery)
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-d-ts.html
Demonstrates how a global library like jQuery is used by directly referencing its global variable '$'.
```typescript
$( () => {
console.log("hello!");
});
```
--------------------------------
### Namespace Type Access Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Demonstrates accessing a type within nested namespaces.
```typescript
let x: A.B.C;
```
--------------------------------
### Value Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Creates a runtime value using a let declaration.
```typescript
let x = 5;
```
--------------------------------
### Importing a JavaScript Module
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html
Example of how to import and use a JavaScript module that exports a function. This demonstrates typical usage patterns.
```typescript
import greeter from "super-greeter";
greeter(2);
greeter("Hello world");
```
--------------------------------
### Equivalent Map Structure for Map.groupBy
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-4.html
Illustrates the equivalent Map object that would be produced by the Map.groupBy example.
```js
const myObj = new Map();
myObj.set("even", [0, 2, 4]);
myObj.set("odd", [1, 3, 5]);
```
--------------------------------
### Equivalent Object Structure for Object.groupBy
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-4.html
Illustrates the equivalent plain JavaScript object structure that would be produced by the Object.groupBy example.
```js
const myObj = {
even: [0, 2, 4],
odd: [1, 3, 5],
};
```
--------------------------------
### SafeBox Class with Distinct Getter and Setter Types
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-1.html
An example of a class `SafeBox` that utilizes distinct types for its `get` and `set` accessors. The `set` accessor only accepts strings, while the `get` accessor can return `undefined`, demonstrating type safety and handling uninitialized states.
```typescript
class SafeBox {
#value: string | undefined;
// Only accepts strings!
set value(newValue: string) {
}
// Must check for 'undefined'!
get value(): string | undefined {
return this.#value;
}
}
```
--------------------------------
### Example --explainFiles Output
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html
Illustrates the typical output format of `--explainFiles`, showing reasons for including library files and local project files.
```text
TS_Compiler_Directory/4.2.2/lib/lib.es5.d.ts
Library referenced via 'es5' from file 'TS_Compiler_Directory/4.2.2/lib/lib.es2015.d.ts'
TS_Compiler_Directory/4.2.2/lib/lib.es2015.d.ts
Library referenced via 'es2015' from file 'TS_Compiler_Directory/4.2.2/lib/lib.es2016.d.ts'
TS_Compiler_Directory/4.2.2/lib/lib.es2016.d.ts
Library referenced via 'es2016' from file 'TS_Compiler_Directory/4.2.2/lib/lib.es2017.d.ts'
TS_Compiler_Directory/4.2.2/lib/lib.es2017.d.ts
Library referenced via 'es2017' from file 'TS_Compiler_Directory/4.2.2/lib/lib.es2018.d.ts'
TS_Compiler_Directory/4.2.2/lib/lib.es2018.d.ts
Library referenced via 'es2018' from file 'TS_Compiler_Directory/4.2.2/lib/lib.es2019.d.ts'
TS_Compiler_Directory/4.2.2/lib/lib.es2019.d.ts
Library referenced via 'es2019' from file 'TS_Compiler_Directory/4.2.2/lib/lib.es2020.d.ts'
TS_Compiler_Directory/4.2.2/lib/lib.es2020.d.ts
Library referenced via 'es2020' from file 'TS_Compiler_Directory/4.2.2/lib/lib.esnext.d.ts'
TS_Compiler_Directory/4.2.2/lib/lib.esnext.d.ts
Library 'lib.esnext.d.ts' specified in compilerOptions
... More Library References...
foo.ts
Matched by include pattern '**/*' in 'tsconfig.json'
```
--------------------------------
### UMD Module Usage (Browser)
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html
Example of using a UMD library like Moment.js in a vanilla browser environment where it's available globally.
```javascript
console.log(moment.format());
```
--------------------------------
### Shorthand Ambient Module Declaration
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html
Declare a module using `declare module "module-name";` to quickly get started. Imports from such modules will have the `any` type.
```typescript
declare module "hot-new-module";
```
```typescript
import x, { y } from "hot-new-module";
x(y);
```
--------------------------------
### Using Paths for Convenience Aliases
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
Illustrates configuring 'paths' to create convenience aliases for application modules, commonly used with bundlers to map shorter paths to source directories.
```json
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"paths": {
"@app/*": ["./src/*"]
}
}
}
```
--------------------------------
### Class with Separate Read and Write Types for Property
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-3.html
This TypeScript example demonstrates the new feature in 4.3, allowing the 'set' accessor to accept a broader type (string | number | boolean) while the 'get' accessor guarantees a 'number'.
```ts
class Thing {
#size = 0;
get size(): number {
return this.#size;
}
set size(value: string | number | boolean) {
let num = Number(value);
// Don't allow NaN and stuff.
if (!Number.isFinite(num)) {
this.#size = 0;
return;
}
this.#size = num;
}
}
Try
```
--------------------------------
### Importing Modules with Subpath Imports
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-6-0.html
Example of importing a module using the configured subpath import alias. This replaces the need for long relative paths.
```js
import * as utils from "#/dist/utils.js";
```
--------------------------------
### Build Library With Declarations
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html
Use this command to build a library and include declaration files, suitable for production builds.
```sh
tsc --build -p ./my-project-dir --declaration
```
--------------------------------
### Import Elision Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html
Demonstrates how TypeScript elides imports that are only used for type information, resulting in cleaner JavaScript output.
```typescript
import { Car } from "./car";
export function drive(car: Car) {
// ...
}
```
```javascript
export function drive(car) {
// ...
}
```
--------------------------------
### Using a Module Plugin
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-plugin-d-ts.html
Demonstrates how to import and use a library, then extend its functionality at runtime using a module plugin declaration.
```typescript
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();
```
--------------------------------
### Handling Various Module Import Syntaxes
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
Demonstrates common ways to import modules in modern JavaScript and TypeScript. These examples show the flexibility required for a module to be compatible with different import styles.
```typescript
const fastify = require("fastify");
const { fastify } = require("fastify");
import fastify = require("fastify");
import * as Fastify from "fastify";
import { fastify, FastifyInstance } from "fastify";
import fastify from "fastify";
import fastify, { FastifyInstance } from "fastify";
```
--------------------------------
### Well-typed Decorator Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html
This example demonstrates how to write a well-typed decorator function by explicitly modeling the types of `this`, arguments, and return values.
```typescript
function loggedMethod(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext Return>
) {
const methodName = String(context.name);
function replacementMethod(this: This, ...args: Args): Return {
console.log(`LOG: Entering method '${methodName}'.`)
const result = target.call(this, ...args);
console.log(`LOG: Exiting method '${methodName}'.`)
return result;
}
return replacementMethod;
}
```
--------------------------------
### Package-Relative Path Resolution Examples
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
Demonstrates how package-relative paths are resolved in `--moduleResolution nodenext`. Imports require a `.js` extension, while `require` calls do not.
```typescript
// @Filename: module.mts
import "pkg/dist/foo"; // ", import, needs ".js" extension
import "pkg/dist/foo.js"; // ",
import foo = require("pkg/dist/foo"); // ", require, no extension needed
```
--------------------------------
### Type Definition Example for Unconstrained Generics
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-8.html
An example illustrating how unconstrained generics can affect type definitions, specifically with nested generic interfaces.
```typescript
interface Foo {
x: Bar;
}
interface Bar { }
```
--------------------------------
### Decorator Implementation Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-5.html
Provides an example of custom decorators `readonly` and `enumerable` applied to a class method. Decorators modify property descriptors.
```typescript
class C {
@readonly
@enumerable(false)
method() { ... }
}
function readonly(target, key, descriptor) {
descriptor.writable = false;
}
function enumerable(value) {
return function (target, key, descriptor) {
descriptor.enumerable = value;
};
}
```
--------------------------------
### Basic Module Resolution Example
Source: https://www.typescriptlang.org/docs/handbook/modules/theory.html
Illustrates a simple module import and export in TypeScript. Ensure that the import path correctly references the exported module.
```typescript
// @Filename: math.ts
export function add(a: number, b: number) {
return a + b;
}
// @Filename: main.ts
import { add } from "./math";
add(1, 2);
```
--------------------------------
### Function Signature Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-9.html
This is an example of a function signature that might be used in documentation. It shows a function `drawButton` that accepts an `options` parameter of type `Options` and returns `void`.
```typescript
export function drawButton(options: Options): void
```
--------------------------------
### Concatenate AMD and System modules with outFile
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html
This example shows how to concatenate AMD and System modules into a single output file using the `outFile` option. The output demonstrates the generated JavaScript with module closures.
```typescript
// file src/a.ts
import * as B from "./lib/b";
export function createA() {
return B.createB();
}
```
```typescript
// file src/lib/b.ts
export function createB() {
return {};
}
```
```javascript
define("lib/b", ["require", "exports"], function (require, exports) {
"use strict";
function createB() {
return {};
}
exports.createB = createB;
});
define("a", ["require", "exports", "lib/b"], function (require, exports, B) {
"use strict";
function createA() {
return B.createB();
}
exports.createA = createA;
});
```
--------------------------------
### Using --lib Flag on Command Line
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html
Demonstrates how to use the --lib flag on the command line to specify included built-in API declaration groups.
```bash
tsc --target es5 --lib es5,es2015.promise
```
--------------------------------
### TypeScript UMD Module Example
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
Example of a TypeScript file designed for AMD or CommonJS loaders, not exposing a global variable. Use a bundler instead for modern development.
```typescript
// @Filename: main.ts
import x, { y, z } from "mod";
import * as mod from "mod";
const dynamic = import("mod");
console.log(x, y, z, mod, dynamic);
export const e1 = 0;
export default "default export";
```
--------------------------------
### Conditional Type Optimization Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html
Demonstrates how TypeScript preserves type information in conditional types. This example shows the need for TypeScript to remember that `A` must be an `Animal` when checking `Zoo`.
```typescript
interface Zoo {
// ...
}
type MakeZoo = A extends Animal ? Zoo : never;
```
--------------------------------
### Using `super` for Base Class Methods
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-3.html
Demonstrates how to call a method from a base class using the `super` keyword in JavaScript.
```javascript
class Base {
someMethod() {
console.log("Base method called!");
}
}
class Derived extends Base {
someMethod() {
console.log("Derived method called!");
super.someMethod();
}
}
new Derived().someMethod();
// Prints:
// Derived method called!
// Base method called!
```
--------------------------------
### Type Name Example with Conditional Types
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html
Illustrates how conditional types can be used to determine the type name of a given type. This example checks for primitive types and functions before defaulting to 'object'.
```typescript
type TypeName = T extends string
? "string"
: T extends number
? "number"
: T extends boolean
? "boolean"
: T extends undefined
? "undefined"
: T extends Function
? "function"
: "object";
type T0 = TypeName; // "string"
type T1 = TypeName<"a">; // "string"
type T2 = TypeName; // "boolean"
type T3 = TypeName<() => void>; // "function"
type T4 = TypeName; // "object"
```
--------------------------------
### Discriminant Property Type Checking Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html
This example demonstrates how TypeScript handles discriminant properties in union types. It shows a scenario where an incorrect assignment would typically cause an error, highlighting the type safety checks.
```typescript
interface Foo {
kind: "foo";
value: string;
}
interface Bar {
kind: "bar";
value: number;
}
function doSomething(x: Foo | Bar) {
if (x.kind === "foo") {
x.value.toLowerCase();
}
}
// uh-oh - luckily TypeScript errors here!
doSomething({
kind: "foo",
value: 123
});
```
--------------------------------
### Redirecting --explainFiles Output
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html
Redirect the verbose output of `--explainFiles` to a text file for easier review, or pipe it to utilities like `less` or VS Code.
```sh
# Forward output to a text file
tsc --explainFiles > explanation.txt
```
```sh
# Pipe output to a utility program like `less`, or an editor like VS Code
tsc --explainFiles | less
```
```sh
tsc --explainFiles | code -
```
--------------------------------
### Generator `yield` Type Inference Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-6.html
This example demonstrates how TypeScript 3.6 infers the type of values passed into a generator via `next()`. The first call to `next()` is ignored, and subsequent calls are type-checked against the expected input type.
```typescript
function* foo() {
let x: string = yield;
console.log(x.toUpperCase());
}
let x = foo();
x.next(); // first call to 'next' is always ignored
x.next(42); // error! 'number' is not assignable to 'string'
```
--------------------------------
### Function Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Creates a runtime value that is a function.
```typescript
function foo() { }
```
--------------------------------
### Example of ESM/CJS Interoperability with TypeScript
Source: https://www.typescriptlang.org/docs/handbook/modules/appendices/esm-cjs-interop.html
This example demonstrates how TypeScript handles imports from CommonJS modules that are transpiled to ES Modules and true CommonJS modules, alongside local ES Module imports. It requires specific compiler options to be set correctly for accurate checking.
```typescript
// @Filename: node_modules/transpiled-dependency/index.js
exports.__esModule = true;
exports.default = function doSomething() { /* ... */ };
exports.something = "something";
// @Filename: node_modules/true-cjs-dependency/index.js
module.exports = function doSomethingElse() { /* ... */ };
// @Filename: src/sayHello.ts
export default function sayHello() { /* ... */ }
export const hello = "hello";
// @Filename: src/main.ts
import doSomething from "transpiled-dependency";
import doSomethingElse from "true-cjs-dependency";
import sayHello from "./sayHello.js";
```
--------------------------------
### Local and Imported Type Declarations Conflict Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
This example demonstrates a scenario where local and imported type declarations with the same name previously caused confusion. TypeScript 3.7 now correctly identifies this as a duplicate identifier error, requiring explicit handling like renaming or module augmentation.
```typescript
// ./someOtherModule.ts
interface SomeType {
y: string;
}
// ./myModule.ts
import { SomeType } from "./someOtherModule";
export interface SomeType {
x: number;
}
function fn(arg: SomeType) {
console.log(arg.x); // Error! 'x' doesn't exist on 'SomeType'
}
```
--------------------------------
### Using --lib Flag in tsconfig.json
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html
Illustrates how to specify built-in API declaration groups to include in a project using the 'lib' option in tsconfig.json.
```json
{
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
}
```
--------------------------------
### Exposing Global Functions to Different Runtimes
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html
Demonstrates how to expose a function to the global scope for web (window), Node.js (global), or any runtime (globalThis) environments.
```javascript
// Web
window.createGreeting = function (s) {
return "Hello, " + s;
};
// Node
global.createGreeting = function (s) {
return "Hello, " + s;
};
// Potentially any runtime
globalThis.createGreeting = function (s) {
return "Hello, " + s;
};
```
--------------------------------
### CommonJS with `export =`
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
Example of using `export =` syntax for CommonJS modules.
```typescript
// @Filename: main.ts
import mod = require("mod");
console.log(mod);
export = {
p1: true,
p2: false
};
```
```javascript
// @Filename: main.js
"use strict";
const mod = require("mod");
console.log(mod);
module.exports = {
p1: true,
p2: false
};
```
--------------------------------
### Configuring Paths for External Module Aliases
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
Shows how to use the 'paths' compiler option to map a bare module specifier to a local type definition file, useful for scenarios like experimental network imports.
```json
{
"compilerOptions": {
"module": "nodenext",
"paths": {
"https://esm.sh/lodash@4.17.21": ["./node_modules/@types/lodash/index.d.ts"]
}
}
}
```
--------------------------------
### Module Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Creates a value that can contain other values or types.
```typescript
module M { }
```
--------------------------------
### TypeScript Module Format Detection Examples
Source: https://www.typescriptlang.org/docs/handbook/modules/theory.html
Shows specific input file names, their contents, output file names, and the resulting module kind based on Node.js rules and TypeScript's interpretation.
```text
Input file name | Contents | Output file name | Module kind | Reason
---|---|---|---|---
/package.json | {} | | |
/main.mts | | /main.mjs | ESM | File extension
/utils.cts | | /utils.cjs | CJS | File extension
/example.ts | | /example.js | CJS | No "type": "module" in package.json
/node_modules/pkg/package.json | { "type": "module" } | | |
/node_modules/pkg/index.d.ts | | | ESM | "type": "module" in package.json
/node_modules/pkg/index.d.cts | | | CJS | File extension
```
--------------------------------
### Namespace Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Creates a value that can contain other values or types.
```typescript
namespace A { namespace B { namespace C { } } }
```
--------------------------------
### Import statement in TypeScript
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
An example of a basic import statement in a TypeScript file.
```typescript
// index.ts
import { foo } from "pkg";
```
--------------------------------
### Exporting a Function in CJS
Source: https://www.typescriptlang.org/docs/handbook/modules/appendices/esm-cjs-interop.html
An example of a CommonJS module exporting a function directly.
```javascript
// @Filename: exports-function.js
module.exports = function hello() {
console.log("Hello, world!");
};
```
--------------------------------
### Configure File and Directory Watching Strategies
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html
Use the `watchOptions` field in `tsconfig.json` or `jsconfig.json` to customize how the compiler/language service watches files and directories. This is useful for optimizing performance based on project needs.
```json
{
"compilerOptions": {
"target": "es2020",
"moduleResolution": "node"
// ...
},
// NEW: Options for file/directory watching
"watchOptions": {
// Use native file system events for files and directories
"watchFile": "useFsEvents",
"watchDirectory": "useFsEvents",
// Poll files for updates more frequently
// when they're updated a lot.
"fallbackPolling": "dynamicPriority"
}
}
```
--------------------------------
### Example Usage of Global-Modifying Modules
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html
Demonstrates how global-modifying modules are typically used with 'require' calls and how they add new methods to built-in types like String and Array.
```javascript
// '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());
```
--------------------------------
### Interface Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Introduces a new type name using an interface.
```typescript
interface I { x: number[]; }
```
--------------------------------
### De-sugared Auto-Accessors
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html
Auto-accessors are transpiled into private properties with `get` and `set` accessors.
```typescript
class Person {
#__name: string;
get name() {
return this.#__name;
}
set name(value: string) {
this.#__name = value;
}
constructor(name: string) {
this.name = name;
}
}
```
--------------------------------
### Recommended Compiler Options for Libraries
Source: https://www.typescriptlang.org/docs/handbook/modules/guides/choosing-compiler-options.html
A JSON configuration object showing recommended compiler options for library authors. Key settings include module resolution, target ECMAScript version, and strictness.
```json
{
"compilerOptions": {
"module": "node18",
"target": "es2020",
"strict": true,
"verbatimModuleSyntax": true,
"declaration": true,
"sourceMap": true,
"declarationMap": true,
"rootDir": "src",
"outDir": "dist"
}
}
```
--------------------------------
### Example of TypeScript files for declaration generation
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-5.html
These TypeScript files demonstrate a simple function and its imported variables, used to illustrate the process of generating declaration files.
```typescript
// util.ts
export let one = "1";
export let two = "2";
// add.ts
import { one, two } from "./util";
export function add() { return one + two; }
```
```typescript
// add.d.ts
export declare function add(): string;
```
--------------------------------
### Enum Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Introduces a new type name using an enum declaration.
```typescript
enum E { A, B, C }
```
--------------------------------
### import.meta Support in SystemJS
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-6.html
Shows how `import.meta` is transformed to `context.meta` when the module target is set to `system`.
```typescript
// This module:\nconsole.log(import.meta.url);\n// gets turned into the following:\nSystem.register([], function (exports, context) {\n return {\n setters: [],\n execute: function () {\n console.log(context.meta.url);\n },\n };\n});\n
```
--------------------------------
### Class Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Introduces a new type name using a class declaration.
```typescript
class C { }
```
--------------------------------
### Preserving baseUrl lookup root with explicit path mapping
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-6-0.html
If `baseUrl` was used as a lookup root, add an explicit path mapping for `*` to preserve the old behavior. This example demonstrates how to replace `baseUrl` with a catch-all path mapping.
```json
{
"compilerOptions": {
// ...
"paths": {
// A new catch-all that replaces the baseUrl:
"*": ["./src/*"],
// Every other path now has an explicit common prefix:
"@app/*": ["./src/app/*"],
"@lib/*": ["./src/lib/*"],
}
}
}
```
--------------------------------
### Extending a Base tsconfig.json
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-5.html
Example of extending a base tsconfig.json file. Paths are relative to the file itself.
```json
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist"
}
}
```
--------------------------------
### Instance Index Signatures in Classes
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-3.html
Demonstrates how to declare an index signature on the instance side of a class, allowing for dynamic properties compatible with the signature.
```typescript
class Foo {
hello = "hello";
world = 1234;
// This is an index signature:
[propName: string]: string | number | undefined;
}
let instance = new Foo();
// Valid assignment
instance["whatever"] = 42;
// Has type 'string | number | undefined'.
let x = instance["something"];
```
--------------------------------
### Type Alias Declaration Example
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Introduces a new type name using a type alias.
```typescript
type sn = number | string;
```
--------------------------------
### Generator Function Example
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-6.html
Demonstrates a generator function that yields string values and returns a final number.
```typescript
function abc123() {
yield "a";
yield "b";
yield "c";
return 123;
}
const iter = abc123();
iter.next(); // { value: "a", done: false }
iter.next(); // { value: "b", done: false }
iter.next(); // { value: "c", done: false }
iter.next(); // { value: 123, done: true }
```
--------------------------------
### Unused Label Detection
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html
Shows an example of an unused label error. The `allowUnusedLabels` option can disable this check.
```typescript
loop: while (x > 0) {
// Error: Unused label.
x++;
}
```
--------------------------------
### Use `/// ` in Declaration Files
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html
Prefer `/// ` over `/// ` in declaration files to correctly reference other packages.
```typescript
///
....
```
--------------------------------
### Configure project files with glob patterns
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html
Use `include` and `exclude` properties in `tsconfig.json` to specify files using glob patterns. Supported wildcards are `*`, `?`, and `**/`.
```json
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
```
--------------------------------
### Corresponding Declaration File Layout
Source: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
Shows the expected directory structure for declaration files that mirrors the library's file layout.
```plaintext
@types/myLib
+---- index.d.ts
+---- foo.d.ts
+---- bar
+---- index.d.ts
+---- baz.d.ts
```
--------------------------------
### Ambient Getters and Setters
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-6.html
Illustrates the allowance of `get` and `set` accessors in ambient contexts, such as in `.d.ts` files.
```typescript
declare class Foo {\n // Allowed in 3.6+.\n get x(): number;\n set x(val: number);\n}\n
```
--------------------------------
### TypeScript File Extension Substitution Example
Source: https://www.typescriptlang.org/docs/handbook/modules/reference.html
Demonstrates how TypeScript resolves a module specifier with a '.js' extension to a '.ts' or '.d.ts' file, mimicking runtime behavior.
```typescript
import x from "./mod.js";
// Runtime lookup: "./mod.js"
// TypeScript lookup #1: "./mod.ts"
// TypeScript lookup #2: "./mod.d.ts"
// TypeScript lookup #3: "./mod.js"
```
--------------------------------
### Migrating paths from baseUrl to paths in tsconfig.json
Source: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-6-0.html
When `baseUrl` is removed, update `paths` to include the prefix explicitly. This example shows how to migrate from using `baseUrl` as a prefix to directly specifying the prefix in `paths`.
```json
{
"compilerOptions": {
// ...
"paths": {
"@app/*": ["./src/app/*"],
"@lib/*": ["./src/lib/*"]
}
}
}
```