CoolFace
Datasetpublic

enigmare/v2-crawler

sourceHugging Faceupdated 29d agoView on Hugging Face
1likes889downloads
typescriptlang_org.jsonl66 linesDownload Raw Back to documentation
1{"id":"doc-typescript_documentation_typescript_for_the_new_-059677a5","source":"documentation","title":"TypeScript: Documentation - TypeScript for the New Programmer","url":"https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html","text":"Example:\n```text\nif (\"\" == 0) {  // It is! But why??}if (1 < x < 3) {  // True for *any* value of x!}\n```\n\nExample:\n```text\nconst obj = { width: 10, height: 15 };// Why is this NaN? Spelling is hard!const area = obj.width * obj.heigth;\n```\n\nExample:\n```text\nconst obj = { width: 10, height: 15 };const area = obj.width * obj.heigth;Property 'heigth' does not exist on type '{ width: number; height: number; }'. Did you mean 'height'?2551Property 'heigth' does not exist on type '{ width: number; height: number; }'. Did you mean 'height'?\n```\n\nExample:\n```text\nlet a = (4')' expected.1005')' expected.\n```\n\nExample:\n```text\nconsole.log(4 / []);\n```\n\nExample:\n```text\nconsole.log(4 / []);The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.2363The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.334Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":31,"estimatedTokens":230}}2{"id":"doc-typescript_documentation_the_basics-208a14bd","source":"documentation","title":"TypeScript: Documentation - The Basics","url":"https://www.typescriptlang.org/docs/handbook/2/basic-types.html","text":"Example:\n```text\n// Accessing the property 'toLowerCase'// on 'message' and then calling itmessage.toLowerCase();// Calling 'message'message();\n```\n\nExample:\n```text\nconst message = \"Hello World!\";\n```\n\nExample:\n```text\nTypeError: message is not a function\n```\n\nExample:\n```text\nfunction fn(x) {  return x.flip();}\n```\n\nExample:\n```text\nconst message = \"hello!\"; message();This expression is not callable.\n  Type 'String' has no call signatures.2349This expression is not callable.\n  Type 'String' has no call signatures.\n```\n\nExample:\n```text\nconst user = {  name: \"Daniel\",  age: 26,};user.location; // returns undefined\n```\n\nExample:\n```text\nconst user = {  name: \"Daniel\",  age: 26,}; user.location;Property 'location' does not exist on type '{ name: string; age: number; }'.2339Property 'location' does not exist on type '{ name: string; age: number; }'.\n```\n\nExample:\n```text\nconst announcement = \"Hello World!\"; // How quickly can you spot the typos?announcement.toLocaleLowercase();announcement.toLocalLowerCase(); // We probably meant to write this...announcement.toLocaleLowerCase();\n```\n\nExample:\n```text\nfunction flipCoin() {  // Meant to be Math.random()  return Math.random < 0.5;Operator '<' cannot be applied to types '() => number' and 'number'.2365Operator '<' cannot be applied to types '() => number' and 'number'.}\n```\n\nExample:\n```text\nconst value = Math.random() < 0.5 ? \"a\" : \"b\";if (value !== \"a\") {  // ...} else if (value === \"b\") {This comparison appears to be unintentional because the types '\"a\"' and '\"b\"' have no overlap.2367This comparison appears to be unintentional because the types '\"a\"' and '\"b\"' have no overlap.  // Oops, unreachable}\n```\n\nExample:\n```text\nimport express from \"express\";const app = express(); app.get(\"/\", function (req, res) {  res.sen         sendsendDatesendFilesendStatus}); app.listen(3000);\n```\n\nExample:\n```text\nnpm install -g typescript\n```\n\nExample:\n```text\n// Greets the world.console.log(\"Hello world!\");\n```\n\nExample:\n```text\ntsc hello.ts\n```\n\nExample:\n```text\n// This is an industrial-grade general-purpose greeter function:function greet(person, date) {  console.log(`Hello ${person}, today is ${date}!`);} greet(\"Brendan\");\n```\n\nExample:\n```text\nExpected 2 arguments, but got 1.\n```\n\nExample:\n```text\ntsc --noEmitOnError hello.ts\n```\n\nExample:\n```text\nfunction greet(person: string, date: Date) {  console.log(`Hello ${person}, today is ${date.toDateString()}!`);}\n```\n\nExample:\n```text\nfunction greet(person: string, date: Date) {  console.log(`Hello ${person}, today is ${date.toDateString()}!`);} greet(\"Maddison\", Date());Argument of type 'string' is not assignable to parameter of type 'Date'.2345Argument of type 'string' is not assignable to parameter of type 'Date'.\n```\n\nExample:\n```text\nfunction greet(person: string, date: Date) {  console.log(`Hello ${person}, today is ${date.toDateString()}!`);} greet(\"Maddison\", new Date());\n```\n\nExample:\n```text\nlet msg = \"hello there!\";    let msg: string\n```\n\nExample:\n```text\n\"use strict\";function greet(person, date) {    console.log(\"Hello \".concat(person, \", today is \").concat(date.toDateString(), \"!\"));}greet(\"Maddison\", new Date());\n```\n\nExample:\n```text\n`Hello ${person}, today is ${date.toDateString()}!`;\n```\n\nExample:\n```text\n\"Hello \".concat(person, \", today is \").concat(date.toDateString(), \"!\");\n```\n\nExample:\n```text\nfunction greet(person, date) {  console.log(`Hello ${person}, today is ${date.toDateString()}!`);}greet(\"Maddison\", new Date());\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.335Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":25,"totalLines":128,"estimatedTokens":876}}3{"id":"doc-typescript_documentation_keyof_type_operator-5a02d796","source":"documentation","title":"TypeScript: Documentation - Keyof Type Operator","url":"https://www.typescriptlang.org/docs/handbook/2/keyof-types.html","text":"Example:\n```text\ntype Point = { x: number; y: number };type P = keyof Point;    type P = keyof Point\n```\n\nExample:\n```text\ntype Arrayish = { [n: number]: unknown };type A = keyof Arrayish;    type A = number type Mapish = { [k: string]: boolean };type M = keyof Mapish;    type M = string | number\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.335Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":11,"estimatedTokens":79}}4{"id":"doc-typescript_documentation_deep_dive-ae872ce8","source":"documentation","title":"TypeScript: Documentation - Deep Dive","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html","text":"Example:\n```text\nexport var SomeVar: { a: SomeType };export interface SomeType {  count: number;}\n```\n\nExample:\n```text\nimport * as foo from \"./foo\";let x: foo.SomeType = foo.SomeVar.a;console.log(x.count);\n```\n\nExample:\n```text\nexport var Bar: { a: Bar };export interface Bar {  count: number;}\n```\n\nExample:\n```text\nimport { Bar } from \"./foo\";let x: Bar = Bar.a;console.log(x.count);\n```\n\nExample:\n```text\ninterface Foo {  x: number;}// ... elsewhere ...interface Foo {  y: number;}let a: Foo = ...;console.log(a.x + a.y); // OK\n```\n\nExample:\n```text\nclass Foo {  x: number;}// ... elsewhere ...interface Foo {  y: number;}let a: Foo = ...;console.log(a.x + a.y); // OK\n```\n\nExample:\n```text\nclass C {}// ... elsewhere ...namespace C {  export let x: number;}let y = C.x; // OK\n```\n\nExample:\n```text\nclass C {}// ... elsewhere ...namespace C {  export interface D {}}let y: C.D; // OK\n```\n\nExample:\n```text\nnamespace X {  export interface Y {}  export class Z {}}// ... elsewhere ...namespace X {  export var Y: number;  export namespace Z {    export class C {}  }}type X = string;\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.335Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":46,"estimatedTokens":276}}5{"id":"doc-typescript_documentation_typescript_for_function-f964296c","source":"documentation","title":"TypeScript: Documentation - TypeScript for Functional Programmers","url":"https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html","text":"Example:\n```text\nlet fst: (a: any, b: any) => any = (a, b) => a;// or more precisely:let fst: <T, U>(a: T, b: U) => T = (a, b) => a;\n```\n\nExample:\n```text\nlet o: { n: number; xs: object[] } = { n: 1, xs: [] };\n```\n\nExample:\n```text\n(1).toExponential();// equivalent toNumber.prototype.toExponential.call(1);\n```\n\nExample:\n```text\n// with \"noImplicitAny\": false in tsconfig.json, anys: any[]const anys = [];anys.push(1);anys.push(\"oh no\");anys.push({ anything: \"goes\" });\n```\n\nExample:\n```text\nanys.map(anys[1]); // oh no, \"oh no\" is not a function\n```\n\nExample:\n```text\nlet sepsis = anys[0] + anys[1]; // this could mean anything\n```\n\nExample:\n```text\n// @strict: falselet o = { x: \"hi\", extra: 1 }; // oklet o2: { x: string } = o; // ok\n```\n\nExample:\n```text\ntype One = { p: string };interface Two {  p: string;}class Three {  p = \"Hello\";} let x: One = { p: \"hi\" };let two: Two = x;two = new Three();\n```\n\nExample:\n```text\nfunction start(  arg: string | string[] | (() => string) | { s: string }): string {  // this is super common in JavaScript  if (typeof arg === \"string\") {    return commonCase(arg);  } else if (Array.isArray(arg)) {    return arg.map(commonCase).join(\",\");  } else if (typeof arg === \"function\") {    return commonCase(arg());  } else {    return commonCase(arg.s);  }   function commonCase(s: string): string {    // finally, just convert a string to another string    return s;  }}\n```\n\nExample:\n```text\ntype Combined = { a: number } & { b: string };type Conflicting = { a: number } & { a: string };\n```\n\nExample:\n```text\ndeclare function pad(s: string, n: number, direction: \"left\" | \"right\"): string;pad(\"hi\", 10, \"left\");\n```\n\nExample:\n```text\nlet s = \"right\";pad(\"hi\", 10, s); // error: 'string' is not assignable to '\"left\" | \"right\"'Argument of type 'string' is not assignable to parameter of type '\"left\" | \"right\"'.2345Argument of type 'string' is not assignable to parameter of type '\"left\" | \"right\"'.\n```\n\nExample:\n```text\nlet s: \"left\" | \"right\" = \"right\";pad(\"hi\", 10, s);\n```\n\nExample:\n```text\nlet s = \"I'm a string!\";\n```\n\nExample:\n```text\ndeclare function map<T, U>(f: (t: T) => U, ts: T[]): U[];let sns = map((n) => n.toString(), [1, 2, 3]);\n```\n\nExample:\n```text\ndeclare function map<T, U>(ts: T[], f: (t: T) => U): U[];\n```\n\nExample:\n```text\ndeclare function run<T>(thunk: (t: T) => void): T;let i: { inference: string } = run((o) => {  o.inference = \"INSERT STATE HERE\";});\n```\n\nExample:\n```text\ntype Size = [number, number];let x: Size = [101.1, 999.9];\n```\n\nExample:\n```text\ntype FString = string & { __compileTimeOnly: any };\n```\n\nExample:\n```text\ntype Shape =  | { kind: \"circle\"; radius: number }  | { kind: \"square\"; x: number }  | { kind: \"triangle\"; x: number; y: number };\n```\n\nExample:\n```text\ntype Shape =  | { kind: \"circle\"; radius: number }  | { kind: \"square\"; x: number }  | { kind: \"triangle\"; x: number; y: number }; function area(s: Shape) {  if (s.kind === \"circle\") {    return Math.PI * s.radius * s.radius;  } else if (s.kind === \"square\") {    return s.x * s.x;  } else {    return (s.x * s.y) / 2;  }}\n```\n\nExample:\n```text\nfunction height(s: Shape) {  if (s.kind === \"circle\") {    return 2 * s.radius;  } else {    // s.kind: \"square\" | \"triangle\"    return s.x;  }}\n```\n\nExample:\n```text\nfunction liftArray<T>(t: T): Array<T> {  return [t];}\n```\n\nExample:\n```text\nfunction firstish<T extends { length: number }>(t1: T, t2: T): T {  return t1.length > t2.length ? t1 : t2;}\n```\n\nExample:\n```text\nfunction length<T extends ArrayLike<unknown>>(t: T): number {}function length(t: ArrayLike<unknown>): number {}\n```\n\nExample:\n```text\nfunction length<T extends ArrayLike<unknown>, U>(m: T<U>) {}\n```\n\nExample:\n```text\nimport { value, Type } from \"npm-package\";import { other, Types } from \"./local-package\";import * as prefix from \"../lib/third-package\";\n```\n\nExample:\n```text\nimport f = require(\"single-function-package\");\n```\n\nExample:\n```text\nexport { f };function f() {  return g();}function g() {} // g is not exported\n```\n\nExample:\n```text\nexport function f() { return g() }function g() { }\n```\n\nExample:\n```text\nconst a = [1, 2, 3];a.push(102); // ):a[0] = 101; // D:\n```\n\nExample:\n```text\ninterface Rx {  readonly x: number;}let rx: Rx = { x: 1 };rx.x = 12; // error\n```\n\nExample:\n```text\ninterface X {  x: number;}let rx: Readonly<X> = { x: 1 };rx.x = 12; // error\n```\n\nExample:\n```text\nlet a: ReadonlyArray<number> = [1, 2, 3];let b: readonly number[] = [1, 2, 3];a.push(102); // errorb[0] = 101; // error\n```\n\nExample:\n```text\nlet a = [1, 2, 3] as const;a.push(102); // errora[0] = 101; // error\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.341Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":35,"totalLines":176,"estimatedTokens":1149}}6{"id":"doc-typescript_documentation_typeof_type_operator-33618cf7","source":"documentation","title":"TypeScript: Documentation - Typeof Type Operator","url":"https://www.typescriptlang.org/docs/handbook/2/typeof-types.html","text":"Example:\n```text\n// Prints \"string\"console.log(typeof \"Hello world\");\n```\n\nExample:\n```text\nlet s = \"hello\";let n: typeof s;   let n: string\n```\n\nExample:\n```text\ntype Predicate = (x: unknown) => boolean;type K = ReturnType<Predicate>;    type K = boolean\n```\n\nExample:\n```text\nfunction f() {  return { x: 10, y: 3 };}type P = ReturnType<f>;'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?2749'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?\n```\n\nExample:\n```text\nfunction f() {  return { x: 10, y: 3 };}type P = ReturnType<typeof f>;    type P = {\n    x: number;\n    y: number;\n}\n```\n\nExample:\n```text\n// Meant to use = ReturnType<typeof msgbox>let shouldContinue: typeof msgbox(\"Are you sure you want to continue?\");',' expected.1005',' expected.\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.341Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":34,"estimatedTokens":208}}7{"id":"doc-typescript_documentation_typescript_for_java_c_p-47d774e3","source":"documentation","title":"TypeScript: Documentation - TypeScript for Java/C# Programmers","url":"https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html","text":"Example:\n```text\ninterface Pointlike {  x: number;  y: number;}interface Named {  name: string;} function logPoint(point: Pointlike) {  console.log(\"x = \" + point.x + \", y = \" + point.y);} function logName(x: Named) {  console.log(\"Hello, \" + x.name);} const obj = {  x: 0,  y: 0,  name: \"Origin\",}; logPoint(obj);logName(obj);\n```\n\nExample:\n```text\nclass Empty {} function fn(arg: Empty) {  // do something?} // No error, but this isn't an 'Empty' ?fn({ k: 10 });\n```\n\nExample:\n```text\nclass Car {  drive() {    // hit the gas  }}class Golfer {  drive() {    // hit the ball far  }}// No error?let w: Car = new Golfer();\n```\n\nExample:\n```text\n// C#static void LogType<T>() {    Console.WriteLine(typeof(T).Name);}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.342Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":21,"estimatedTokens":183}}8{"id":"doc-typescript_documentation_everyday_types-1ec6ef05","source":"documentation","title":"TypeScript: Documentation - Everyday Types","url":"https://www.typescriptlang.org/docs/handbook/2/everyday-types.html","text":"Example:\n```text\nlet obj: any = { x: 0 };// None of the following lines of code will throw compiler errors.// Using `any` disables all further type checking, and it is assumed// you know the environment better than TypeScript.obj.foo();obj();obj.bar = 100;obj = \"hello\";const n: number = obj;\n```\n\nExample:\n```text\nlet myName: string = \"Alice\";\n```\n\nExample:\n```text\n// No type annotation needed -- 'myName' inferred as type 'string'let myName = \"Alice\";\n```\n\nExample:\n```text\n// Parameter type annotationfunction greet(name: string) {  console.log(\"Hello, \" + name.toUpperCase() + \"!!\");}\n```\n\nExample:\n```text\n// Would be a runtime error if executed!greet(42);Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.\n```\n\nExample:\n```text\nfunction getFavoriteNumber(): number {  return 26;}\n```\n\nExample:\n```text\nasync function getFavoriteNumber(): Promise<number> {  return 26;}\n```\n\nExample:\n```text\nconst names = [\"Alice\", \"Bob\", \"Eve\"]; // Contextual typing for function - parameter s inferred to have type stringnames.forEach(function (s) {  console.log(s.toUpperCase());}); // Contextual typing also applies to arrow functionsnames.forEach((s) => {  console.log(s.toUpperCase());});\n```\n\nExample:\n```text\n// The parameter's type annotation is an object typefunction printCoord(pt: { x: number; y: number }) {  console.log(\"The coordinate's x value is \" + pt.x);  console.log(\"The coordinate's y value is \" + pt.y);}printCoord({ x: 3, y: 7 });\n```\n\nExample:\n```text\nfunction printName(obj: { first: string; last?: string }) {  // ...}// Both OKprintName({ first: \"Bob\" });printName({ first: \"Alice\", last: \"Alisson\" });\n```\n\nExample:\n```text\nfunction printName(obj: { first: string; last?: string }) {  // Error - might crash if 'obj.last' wasn't provided!  console.log(obj.last.toUpperCase());'obj.last' is possibly 'undefined'.18048'obj.last' is possibly 'undefined'.  if (obj.last !== undefined) {    // OK    console.log(obj.last.toUpperCase());  }   // A safe alternative using modern JavaScript syntax:  console.log(obj.last?.toUpperCase());}\n```\n\nExample:\n```text\nfunction printId(id: number | string) {  console.log(\"Your ID is: \" + id);}// OKprintId(101);// OKprintId(\"202\");// ErrorprintId({ myID: 22342 });Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.2345Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.\n```\n\nExample:\n```text\nfunction printTextOrNumberOrBool(  textOrNumberOrBool:    | string    | number    | boolean) {  console.log(textOrNumberOrBool);}\n```\n\nExample:\n```text\nfunction printId(id: number | string) {  console.log(id.toUpperCase());Property 'toUpperCase' does not exist on type 'string | number'.\n  Property 'toUpperCase' does not exist on type 'number'.2339Property 'toUpperCase' does not exist on type 'string | number'.\n  Property 'toUpperCase' does not exist on type 'number'.}\n```\n\nExample:\n```text\nfunction printId(id: number | string) {  if (typeof id === \"string\") {    // In this branch, id is of type 'string'    console.log(id.toUpperCase());  } else {    // Here, id is of type 'number'    console.log(id);  }}\n```\n\nExample:\n```text\nfunction welcomePeople(x: string[] | string) {  if (Array.isArray(x)) {    // Here: 'x' is 'string[]'    console.log(\"Hello, \" + x.join(\" and \"));  } else {    // Here: 'x' is 'string'    console.log(\"Welcome lone traveler \" + x);  }}\n```\n\nExample:\n```text\n// Return type is inferred as number[] | stringfunction getFirstThree(x: number[] | string) {  return x.slice(0, 3);}\n```\n\nExample:\n```text\ntype Point = {  x: number;  y: number;}; // Exactly the same as the earlier examplefunction printCoord(pt: Point) {  console.log(\"The coordinate's x value is \" + pt.x);  console.log(\"The coordinate's y value is \" + pt.y);} printCoord({ x: 100, y: 100 });\n```\n\nExample:\n```text\ntype ID = number | string;\n```\n\nExample:\n```text\ntype UserInputSanitizedString = string; function sanitizeInput(str: string): UserInputSanitizedString {  return sanitize(str);} // Create a sanitized inputlet userInput = sanitizeInput(getInput()); // Can still be re-assigned with a string thoughuserInput = \"new input\";\n```\n\nExample:\n```text\ninterface Point {  x: number;  y: number;} function printCoord(pt: Point) {  console.log(\"The coordinate's x value is \" + pt.x);  console.log(\"The coordinate's y value is \" + pt.y);} printCoord({ x: 100, y: 100 });\n```\n\nExample:\n```text\ninterface Animal {\n  name: string;\n}\ninterface Bear extends Animal {\n  honey: boolean;\n}\nconst bear = getBear();\nbear.name;\nbear.honey;\n```\n\nExample:\n```text\ntype Animal = {\n  name: string;\n}\ntype Bear = Animal & { \n  honey: boolean;\n}\nconst bear = getBear();\nbear.name;\nbear.honey;\n```\n\nExample:\n```text\ninterface Window {\n  title: string;\n}\ninterface Window {\n  ts: TypeScriptAPI;\n}\nconst src = 'const a = \"Hello World\"';\nwindow.ts.transpileModule(src, {});\n```\n\nExample:\n```text\ntype Window = {\n  title: string;\n}\ntype Window = {\n  ts: TypeScriptAPI;\n}\n // Error: Duplicate identifier 'Window'.\n```\n\nExample:\n```text\nconst myCanvas = document.getElementById(\"main_canvas\") as HTMLCanvasElement;\n```\n\nExample:\n```text\nconst myCanvas = <HTMLCanvasElement>document.getElementById(\"main_canvas\");\n```\n\nExample:\n```text\nconst x = \"hello\" as number;Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.2352Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.\n```\n\nExample:\n```text\nconst a = expr as any as T;\n```\n\nExample:\n```text\nlet changingString = \"Hello World\";changingString = \"Olá Mundo\";// Because `changingString` can represent any possible string, that// is how TypeScript describes it in the type systemchangingString;      let changingString: string const constantString = \"Hello World\";// Because `constantString` can only represent 1 possible string, it// has a literal type representationconstantString;      const constantString: \"Hello World\"\n```\n\nExample:\n```text\nlet x: \"hello\" = \"hello\";// OKx = \"hello\";// ...x = \"howdy\";Type '\"howdy\"' is not assignable to type '\"hello\"'.2322Type '\"howdy\"' is not assignable to type '\"hello\"'.\n```\n\nExample:\n```text\nfunction printText(s: string, alignment: \"left\" | \"right\" | \"center\") {  // ...}printText(\"Hello, world\", \"left\");printText(\"G'day, mate\", \"centre\");Argument of type '\"centre\"' is not assignable to parameter of type '\"left\" | \"right\" | \"center\"'.2345Argument of type '\"centre\"' is not assignable to parameter of type '\"left\" | \"right\" | \"center\"'.\n```\n\nExample:\n```text\nfunction compare(a: string, b: string): -1 | 0 | 1 {  return a === b ? 0 : a > b ? 1 : -1;}\n```\n\nExample:\n```text\ninterface Options {  width: number;}function configure(x: Options | \"auto\") {  // ...}configure({ width: 100 });configure(\"auto\");configure(\"automatic\");Argument of type '\"automatic\"' is not assignable to parameter of type 'Options | \"auto\"'.2345Argument of type '\"automatic\"' is not assignable to parameter of type 'Options | \"auto\"'.\n```\n\nExample:\n```text\nconst obj = { counter: 0 };if (someCondition) {  obj.counter = 1;}\n```\n\nExample:\n```text\ndeclare function handleRequest(url: string, method: \"GET\" | \"POST\"): void; const req = { url: \"https://example.com\", method: \"GET\" };handleRequest(req.url, req.method);Argument of type 'string' is not assignable to parameter of type '\"GET\" | \"POST\"'.2345Argument of type 'string' is not assignable to parameter of type '\"GET\" | \"POST\"'.\n```\n\nExample:\n```text\n// Change 1:const req = { url: \"https://example.com\", method: \"GET\" as \"GET\" };// Change 2handleRequest(req.url, req.method as \"GET\");\n```\n\nExample:\n```text\nconst req = { url: \"https://example.com\", method: \"GET\" } as const;handleRequest(req.url, req.method);\n```\n\nExample:\n```text\nfunction doSomething(x: string | null) {  if (x === null) {    // do nothing  } else {    console.log(\"Hello, \" + x.toUpperCase());  }}\n```\n\nExample:\n```text\nfunction liveDangerously(x?: number | null) {  // No error  console.log(x!.toFixed());}\n```\n\nExample:\n```text\n// Creating a bigint via the BigInt functionconst oneHundred: bigint = BigInt(100); // Creating a BigInt via the literal syntaxconst anotherHundred: bigint = 100n;\n```\n\nExample:\n```text\nconst firstName = Symbol(\"name\");const secondName = Symbol(\"name\"); if (firstName === secondName) {This comparison appears to be unintentional because the types 'typeof firstName' and 'typeof secondName' have no overlap.2367This comparison appears to be unintentional because the types 'typeof firstName' and 'typeof secondName' have no overlap.  // Can't ever happen}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.343Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":42,"totalLines":242,"estimatedTokens":2219}}9{"id":"doc-typescript_documentation_narrowing-b2adaad0","source":"documentation","title":"TypeScript: Documentation - Narrowing","url":"https://www.typescriptlang.org/docs/handbook/2/narrowing.html","text":"Example:\n```text\nfunction padLeft(padding: number | string, input: string): string {  throw new Error(\"Not implemented yet!\");}\n```\n\nExample:\n```text\nfunction padLeft(padding: number | string, input: string): string {  return \" \".repeat(padding) + input;Argument of type 'string | number' is not assignable to parameter of type 'number'.\n  Type 'string' is not assignable to type 'number'.2345Argument of type 'string | number' is not assignable to parameter of type 'number'.\n  Type 'string' is not assignable to type 'number'.}\n```\n\nExample:\n```text\nfunction padLeft(padding: number | string, input: string): string {  if (typeof padding === \"number\") {    return \" \".repeat(padding) + input;  }  return padding + input;}\n```\n\nExample:\n```text\nfunction padLeft(padding: number | string, input: string): string {  if (typeof padding === \"number\") {    return \" \".repeat(padding) + input;                        (parameter) padding: number  }  return padding + input;           (parameter) padding: string}\n```\n\nExample:\n```text\nfunction printAll(strs: string | string[] | null) {  if (typeof strs === \"object\") {    for (const s of strs) {'strs' is possibly 'null'.18047'strs' is possibly 'null'.      console.log(s);    }  } else if (typeof strs === \"string\") {    console.log(strs);  } else {    // do nothing  }}\n```\n\nExample:\n```text\nfunction getUsersOnlineMessage(numUsersOnline: number) {  if (numUsersOnline) {    return `There are ${numUsersOnline} online now!`;  }  return \"Nobody's here. :(\";}\n```\n\nExample:\n```text\n// both of these result in 'true'Boolean(\"hello\"); // type: boolean, value: true!!\"world\"; // type: true,    value: trueThis kind of expression is always truthy.2872This kind of expression is always truthy.\n```\n\nExample:\n```text\nfunction printAll(strs: string | string[] | null) {  if (strs && typeof strs === \"object\") {    for (const s of strs) {      console.log(s);    }  } else if (typeof strs === \"string\") {    console.log(strs);  }}\n```\n\nExample:\n```text\nTypeError: null is not iterable\n```\n\nExample:\n```text\nfunction printAll(strs: string | string[] | null) {  // !!!!!!!!!!!!!!!!  //  DON'T DO THIS!  //   KEEP READING  // !!!!!!!!!!!!!!!!  if (strs) {    if (typeof strs === \"object\") {      for (const s of strs) {        console.log(s);      }    } else if (typeof strs === \"string\") {      console.log(strs);    }  }}\n```\n\nExample:\n```text\nfunction multiplyAll(  values: number[] | undefined,  factor: number): number[] | undefined {  if (!values) {    return values;  } else {    return values.map((x) => x * factor);  }}\n```\n\nExample:\n```text\nfunction example(x: string | number, y: string | boolean) {  if (x === y) {    // We can now call any 'string' method on 'x' or 'y'.    x.toUpperCase();          (method) String.toUpperCase(): string    y.toLowerCase();          (method) String.toLowerCase(): string  } else {    console.log(x);               (parameter) x: string | number    console.log(y);               (parameter) y: string | boolean  }}\n```\n\nExample:\n```text\nfunction printAll(strs: string | string[] | null) {  if (strs !== null) {    if (typeof strs === \"object\") {      for (const s of strs) {                       (parameter) strs: string[]        console.log(s);      }    } else if (typeof strs === \"string\") {      console.log(strs);                   (parameter) strs: string    }  }}\n```\n\nExample:\n```text\ninterface Container {  value: number | null | undefined;} function multiplyValue(container: Container, factor: number) {  // Remove both 'null' and 'undefined' from the type.  if (container.value != null) {    console.log(container.value);                           (property) Container.value: number     // Now we can safely multiply 'container.value'.    container.value *= factor;  }}\n```\n\nExample:\n```text\ntype Fish = { swim: () => void };type Bird = { fly: () => void }; function move(animal: Fish | Bird) {  if (\"swim\" in animal) {    return animal.swim();  }   return animal.fly();}\n```\n\nExample:\n```text\ntype Fish = { swim: () => void };type Bird = { fly: () => void };type Human = { swim?: () => void; fly?: () => void }; function move(animal: Fish | Bird | Human) {  if (\"swim\" in animal) {    animal;      (parameter) animal: Fish | Human  } else {    animal;      (parameter) animal: Bird | Human  }}\n```\n\nExample:\n```text\nfunction logValue(x: Date | string) {  if (x instanceof Date) {    console.log(x.toUTCString());               (parameter) x: Date  } else {    console.log(x.toUpperCase());               (parameter) x: string  }}\n```\n\nExample:\n```text\nlet x = Math.random() < 0.5 ? 10 : \"hello world!\";   let x: string | numberx = 1; console.log(x);           let x: numberx = \"goodbye!\"; console.log(x);           let x: string\n```\n\nExample:\n```text\nlet x = Math.random() < 0.5 ? 10 : \"hello world!\";   let x: string | numberx = 1; console.log(x);           let x: numberx = true;Type 'boolean' is not assignable to type 'string | number'.2322Type 'boolean' is not assignable to type 'string | number'. console.log(x);           let x: string | number\n```\n\nExample:\n```text\nfunction padLeft(padding: number | string, input: string) {  if (typeof padding === \"number\") {    return \" \".repeat(padding) + input;  }  return padding + input;}\n```\n\nExample:\n```text\nfunction example() {  let x: string | number | boolean;   x = Math.random() < 0.5;   console.log(x);             let x: boolean   if (Math.random() < 0.5) {    x = \"hello\";    console.log(x);               let x: string  } else {    x = 100;    console.log(x);               let x: number  }   return x;        let x: string | number}\n```\n\nExample:\n```text\nfunction isFish(pet: Fish | Bird): pet is Fish {  return (pet as Fish).swim !== undefined;}\n```\n\nExample:\n```text\n// Both calls to 'swim' and 'fly' are now okay.let pet = getSmallPet(); if (isFish(pet)) {  pet.swim();} else {  pet.fly();}\n```\n\nExample:\n```text\nconst zoo: (Fish | Bird)[] = [getSmallPet(), getSmallPet(), getSmallPet()];const underWater1: Fish[] = zoo.filter(isFish);// or, equivalentlyconst underWater2: Fish[] = zoo.filter(isFish) as Fish[]; // The predicate may need repeating for more complex examplesconst underWater3: Fish[] = zoo.filter((pet): pet is Fish => {  if (pet.name === \"sharkey\") return false;  return isFish(pet);});\n```\n\nExample:\n```text\ninterface Shape {  kind: \"circle\" | \"square\";  radius?: number;  sideLength?: number;}\n```\n\nExample:\n```text\nfunction handleShape(shape: Shape) {  // oops!  if (shape.kind === \"rect\") {This comparison appears to be unintentional because the types '\"circle\" | \"square\"' and '\"rect\"' have no overlap.2367This comparison appears to be unintentional because the types '\"circle\" | \"square\"' and '\"rect\"' have no overlap.    // ...  }}\n```\n\nExample:\n```text\nfunction getArea(shape: Shape) {  return Math.PI * shape.radius ** 2;'shape.radius' is possibly 'undefined'.18048'shape.radius' is possibly 'undefined'.}\n```\n\nExample:\n```text\nfunction getArea(shape: Shape) {  if (shape.kind === \"circle\") {    return Math.PI * shape.radius ** 2;'shape.radius' is possibly 'undefined'.18048'shape.radius' is possibly 'undefined'.  }}\n```\n\nExample:\n```text\nfunction getArea(shape: Shape) {  if (shape.kind === \"circle\") {    return Math.PI * shape.radius! ** 2;  }}\n```\n\nExample:\n```text\ninterface Circle {  kind: \"circle\";  radius: number;} interface Square {  kind: \"square\";  sideLength: number;} type Shape = Circle | Square;\n```\n\nExample:\n```text\nfunction getArea(shape: Shape) {  return Math.PI * shape.radius ** 2;Property 'radius' does not exist on type 'Shape'.\n  Property 'radius' does not exist on type 'Square'.2339Property 'radius' does not exist on type 'Shape'.\n  Property 'radius' does not exist on type 'Square'.}\n```\n\nExample:\n```text\nfunction getArea(shape: Shape) {  if (shape.kind === \"circle\") {    return Math.PI * shape.radius ** 2;                      (parameter) shape: Circle  }}\n```\n\nExample:\n```text\nfunction getArea(shape: Shape) {  switch (shape.kind) {    case \"circle\":      return Math.PI * shape.radius ** 2;                        (parameter) shape: Circle    case \"square\":      return shape.sideLength ** 2;              (parameter) shape: Square  }}\n```\n\nExample:\n```text\ntype Shape = Circle | Square; function getArea(shape: Shape) {  switch (shape.kind) {    case \"circle\":      return Math.PI * shape.radius ** 2;    case \"square\":      return shape.sideLength ** 2;    default:      const _exhaustiveCheck: never = shape;      return _exhaustiveCheck;  }}\n```\n\nExample:\n```text\ninterface Triangle {  kind: \"triangle\";  sideLength: number;} type Shape = Circle | Square | Triangle; function getArea(shape: Shape) {  switch (shape.kind) {    case \"circle\":      return Math.PI * shape.radius ** 2;    case \"square\":      return shape.sideLength ** 2;    default:      const _exhaustiveCheck: never = shape;Type 'Triangle' is not assignable to type 'never'.2322Type 'Triangle' is not assignable to type 'never'.      return _exhaustiveCheck;  }}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.344Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":35,"totalLines":180,"estimatedTokens":2244}}10{"id":"doc-typescript_documentation_more_on_functions-db1c5af3","source":"documentation","title":"TypeScript: Documentation - More on Functions","url":"https://www.typescriptlang.org/docs/handbook/2/functions.html","text":"Example:\n```text\nfunction greeter(fn: (a: string) => void) {  fn(\"Hello, World\");} function printToConsole(s: string) {  console.log(s);} greeter(printToConsole);\n```\n\nExample:\n```text\ntype GreetFunction = (a: string) => void;function greeter(fn: GreetFunction) {  // ...}\n```\n\nExample:\n```text\ntype DescribableFunction = {  description: string;  (someArg: number): boolean;};function doSomething(fn: DescribableFunction) {  console.log(fn.description + \" returned \" + fn(6));} function myFunc(someArg: number) {  return someArg > 3;}myFunc.description = \"default description\"; doSomething(myFunc);\n```\n\nExample:\n```text\ntype SomeConstructor = {  new (s: string): SomeObject;};function fn(ctor: SomeConstructor) {  return new ctor(\"hello\");}\n```\n\nExample:\n```text\ninterface CallOrConstruct {  (n?: number): string;  new (s: string): Date;} function fn(ctor: CallOrConstruct) {  // Passing an argument of type `number` to `ctor` matches it against  // the first definition in the `CallOrConstruct` interface.  console.log(ctor(10));               (parameter) ctor: CallOrConstruct\n(n?: number) => string   // Similarly, passing an argument of type `string` to `ctor` matches it  // against the second definition in the `CallOrConstruct` interface.  console.log(new ctor(\"10\"));                   (parameter) ctor: CallOrConstruct\nnew (s: string) => Date} fn(Date);\n```\n\nExample:\n```text\nfunction firstElement(arr: any[]) {  return arr[0];}\n```\n\nExample:\n```text\nfunction firstElement<Type>(arr: Type[]): Type | undefined {  return arr[0];}\n```\n\nExample:\n```text\n// s is of type 'string'const s = firstElement([\"a\", \"b\", \"c\"]);// n is of type 'number'const n = firstElement([1, 2, 3]);// u is of type undefinedconst u = firstElement([]);\n```\n\nExample:\n```text\nfunction map<Input, Output>(arr: Input[], func: (arg: Input) => Output): Output[] {  return arr.map(func);} // Parameter 'n' is of type 'string'// 'parsed' is of type 'number[]'const parsed = map([\"1\", \"2\", \"3\"], (n) => parseInt(n));\n```\n\nExample:\n```text\nfunction longest<Type extends { length: number }>(a: Type, b: Type) {  if (a.length >= b.length) {    return a;  } else {    return b;  }} // longerArray is of type 'number[]'const longerArray = longest([1, 2], [1, 2, 3]);// longerString is of type 'alice' | 'bob'const longerString = longest(\"alice\", \"bob\");// Error! Numbers don't have a 'length' propertyconst notOK = longest(10, 100);Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.2345Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.\n```\n\nExample:\n```text\nfunction minimumLength<Type extends { length: number }>(  obj: Type,  minimum: number): Type {  if (obj.length >= minimum) {    return obj;  } else {    return { length: minimum };Type '{ length: number; }' is not assignable to type 'Type'.\n  '{ length: number; }' is assignable to the constraint of type 'Type', but 'Type' could be instantiated with a different subtype of constraint '{ length: number; }'.2322Type '{ length: number; }' is not assignable to type 'Type'.\n  '{ length: number; }' is assignable to the constraint of type 'Type', but 'Type' could be instantiated with a different subtype of constraint '{ length: number; }'.  }}\n```\n\nExample:\n```text\n// 'arr' gets value { length: 6 }const arr = minimumLength([1, 2, 3], 6);// and crashes here because arrays have// a 'slice' method, but not the returned object!console.log(arr.slice(0));\n```\n\nExample:\n```text\nfunction combine<Type>(arr1: Type[], arr2: Type[]): Type[] {  return arr1.concat(arr2);}\n```\n\nExample:\n```text\nconst arr = combine([1, 2, 3], [\"hello\"]);Type 'string' is not assignable to type 'number'.2322Type 'string' is not assignable to type 'number'.\n```\n\nExample:\n```text\nconst arr = combine<string | number>([1, 2, 3], [\"hello\"]);\n```\n\nExample:\n```text\nfunction firstElement1<Type>(arr: Type[]) {  return arr[0];} function firstElement2<Type extends any[]>(arr: Type) {  return arr[0];} // a: number (good)const a = firstElement1([1, 2, 3]);// b: any (bad)const b = firstElement2([1, 2, 3]);\n```\n\nExample:\n```text\nfunction filter1<Type>(arr: Type[], func: (arg: Type) => boolean): Type[] {  return arr.filter(func);} function filter2<Type, Func extends (arg: Type) => boolean>(  arr: Type[],  func: Func): Type[] {  return arr.filter(func);}\n```\n\nExample:\n```text\nfunction greet<Str extends string>(s: Str) {  console.log(\"Hello, \" + s);} greet(\"world\");\n```\n\nExample:\n```text\nfunction greet(s: string) {  console.log(\"Hello, \" + s);}\n```\n\nExample:\n```text\nfunction f(n: number) {  console.log(n.toFixed()); // 0 arguments  console.log(n.toFixed(3)); // 1 argument}\n```\n\nExample:\n```text\nfunction f(x?: number) {  // ...}f(); // OKf(10); // OK\n```\n\nExample:\n```text\nfunction f(x = 10) {  // ...}\n```\n\nExample:\n```text\n// All OKf();f(10);f(undefined);\n```\n\nExample:\n```text\nfunction myForEach(arr: any[], callback: (arg: any, index?: number) => void) {  for (let i = 0; i < arr.length; i++) {    callback(arr[i], i);  }}\n```\n\nExample:\n```text\nmyForEach([1, 2, 3], (a) => console.log(a));myForEach([1, 2, 3], (a, i) => console.log(a, i));\n```\n\nExample:\n```text\nfunction myForEach(arr: any[], callback: (arg: any, index?: number) => void) {  for (let i = 0; i < arr.length; i++) {    // I don't feel like providing the index today    callback(arr[i]);  }}\n```\n\nExample:\n```text\nmyForEach([1, 2, 3], (a, i) => {  console.log(i.toFixed());'i' is possibly 'undefined'.18048'i' is possibly 'undefined'.});\n```\n\nExample:\n```text\nfunction makeDate(timestamp: number): Date;function makeDate(m: number, d: number, y: number): Date;function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {  if (d !== undefined && y !== undefined) {    return new Date(y, mOrTimestamp, d);  } else {    return new Date(mOrTimestamp);  }}const d1 = makeDate(12345678);const d2 = makeDate(5, 5, 5);const d3 = makeDate(1, 3);No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.2575No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.\n```\n\nExample:\n```text\nfunction fn(x: string): void;function fn() {  // ...}// Expected to be able to call with zero argumentsfn();Expected 1 arguments, but got 0.2554Expected 1 arguments, but got 0.\n```\n\nExample:\n```text\nfunction fn(x: boolean): void;// Argument type isn't rightfunction fn(x: string): void;This overload signature is not compatible with its implementation signature.2394This overload signature is not compatible with its implementation signature.function fn(x: boolean) {}\n```\n\nExample:\n```text\nfunction fn(x: string): string;// Return type isn't rightfunction fn(x: number): boolean;This overload signature is not compatible with its implementation signature.2394This overload signature is not compatible with its implementation signature.function fn(x: string | number) {  return \"oops\";}\n```\n\nExample:\n```text\nfunction len(s: string): number;function len(arr: any[]): number;function len(x: any) {  return x.length;}\n```\n\nExample:\n```text\nlen(\"\"); // OKlen([0]); // OKlen(Math.random() > 0.5 ? \"hello\" : [0]);No overload matches this call.\n  Overload 1 of 2, '(s: string): number', gave the following error.\n    Argument of type 'number[] | \"hello\"' is not assignable to parameter of type 'string'.\n      Type 'number[]' is not assignable to type 'string'.\n  Overload 2 of 2, '(arr: any[]): number', gave the following error.\n    Argument of type 'number[] | \"hello\"' is not assignable to parameter of type 'any[]'.\n      Type 'string' is not assignable to type 'any[]'.2769No overload matches this call.\n  Overload 1 of 2, '(s: string): number', gave the following error.\n    Argument of type 'number[] | \"hello\"' is not assignable to parameter of type 'string'.\n      Type 'number[]' is not assignable to type 'string'.\n  Overload 2 of 2, '(arr: any[]): number', gave the following error.\n    Argument of type 'number[] | \"hello\"' is not assignable to parameter of type 'any[]'.\n      Type 'string' is not assignable to type 'any[]'.\n```\n\nExample:\n```text\nfunction len(x: any[] | string) {  return x.length;}\n```\n\nExample:\n```text\nconst user = {  id: 123,   admin: false,  becomeAdmin: function () {    this.admin = true;  },};\n```\n\nExample:\n```text\ninterface DB {  filterUsers(filter: (this: User) => boolean): User[];} const db = getDB();const admins = db.filterUsers(function (this: User) {  return this.admin;});\n```\n\nExample:\n```text\ninterface DB {  filterUsers(filter: (this: User) => boolean): User[];} const db = getDB();const admins = db.filterUsers(() => this.admin);The containing arrow function captures the global value of 'this'.Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.70417017The containing arrow function captures the global value of 'this'.Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.\n```\n\nExample:\n```text\n// The inferred return type is voidfunction noop() {  return;}\n```\n\nExample:\n```text\nfunction f1(a: any) {  a.b(); // OK}function f2(a: unknown) {  a.b();'a' is of type 'unknown'.18046'a' is of type 'unknown'.}\n```\n\nExample:\n```text\nfunction safeParse(s: string): unknown {  return JSON.parse(s);} // Need to be careful with 'obj'!const obj = safeParse(someRandomString);\n```\n\nExample:\n```text\nfunction fail(msg: string): never {  throw new Error(msg);}\n```\n\nExample:\n```text\nfunction fn(x: string | number) {  if (typeof x === \"string\") {    // do something  } else if (typeof x === \"number\") {    // do something else  } else {    x; // has type 'never'!  }}\n```\n\nExample:\n```text\nfunction doSomething(f: Function) {  return f(1, 2, 3);}\n```\n\nExample:\n```text\nfunction multiply(n: number, ...m: number[]) {  return m.map((x) => n * x);}// 'a' gets value [10, 20, 30, 40]const a = multiply(10, 1, 2, 3, 4);\n```\n\nExample:\n```text\nconst arr1 = [1, 2, 3];const arr2 = [4, 5, 6];arr1.push(...arr2);\n```\n\nExample:\n```text\n// Inferred type is number[] -- \"an array with zero or more numbers\",// not specifically two numbersconst args = [8, 5];const angle = Math.atan2(...args);A spread argument must either have a tuple type or be passed to a rest parameter.2556A spread argument must either have a tuple type or be passed to a rest parameter.\n```\n\nExample:\n```text\n// Inferred as 2-length tupleconst args = [8, 5] as const;// OKconst angle = Math.atan2(...args);\n```\n\nExample:\n```text\nfunction sum({ a, b, c }) {  console.log(a + b + c);}sum({ a: 10, b: 3, c: 9 });\n```\n\nExample:\n```text\nfunction sum({ a, b, c }: { a: number; b: number; c: number }) {  console.log(a + b + c);}\n```\n\nExample:\n```text\n// Same as prior exampletype ABC = { a: number; b: number; c: number };function sum({ a, b, c }: ABC) {  console.log(a + b + c);}\n```\n\nExample:\n```text\ntype voidFunc = () => void; const f1: voidFunc = () => {  return true;}; const f2: voidFunc = () => true; const f3: voidFunc = function () {  return true;};\n```\n\nExample:\n```text\nconst v1 = f1(); const v2 = f2(); const v3 = f3();\n```\n\nExample:\n```text\nconst src = [1, 2, 3];const dst = [0]; src.forEach((el) => dst.push(el));\n```\n\nExample:\n```text\nfunction f2(): void {  // @ts-expect-error  return true;} const f3 = function (): void {  // @ts-expect-error  return true;};\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.346Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":54,"totalLines":287,"estimatedTokens":2818}}11{"id":"doc-typescript_documentation_indexed_access_types-75c2147e","source":"documentation","title":"TypeScript: Documentation - Indexed Access Types","url":"https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html","text":"Example:\n```text\ntype Person = { age: number; name: string; alive: boolean };type Age = Person[\"age\"];     type Age = number\n```\n\nExample:\n```text\ntype I1 = Person[\"age\" | \"name\"];     type I1 = string | number type I2 = Person[keyof Person];     type I2 = string | number | boolean type AliveOrName = \"alive\" | \"name\";type I3 = Person[AliveOrName];     type I3 = string | boolean\n```\n\nExample:\n```text\ntype I1 = Person[\"alve\"];Property 'alve' does not exist on type 'Person'.2339Property 'alve' does not exist on type 'Person'.\n```\n\nExample:\n```text\nconst MyArray = [  { name: \"Alice\", age: 15 },  { name: \"Bob\", age: 23 },  { name: \"Eve\", age: 38 },]; type Person = typeof MyArray[number];       type Person = {\n    name: string;\n    age: number;\n}type Age = typeof MyArray[number][\"age\"];     type Age = number// Ortype Age2 = Person[\"age\"];      type Age2 = number\n```\n\nExample:\n```text\nconst key = \"age\";type Age = Person[key];Type 'key' cannot be used as an index type.'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?25382749Type 'key' cannot be used as an index type.'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?\n```\n\nExample:\n```text\ntype key = \"age\";type Age = Person[key];\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.346Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":34,"estimatedTokens":320}}12{"id":"doc-typescript_documentation_generics-b8c0426b","source":"documentation","title":"TypeScript: Documentation - Generics","url":"https://www.typescriptlang.org/docs/handbook/2/generics.html","text":"Example:\n```text\nfunction identity(arg: number): number {  return arg;}\n```\n\nExample:\n```text\nfunction identity(arg: any): any {  return arg;}\n```\n\nExample:\n```text\nfunction identity<Type>(arg: Type): Type {  return arg;}\n```\n\nExample:\n```text\nlet output = identity<string>(\"myString\");      let output: string\n```\n\nExample:\n```text\nlet output = identity(\"myString\");      let output: string\n```\n\nExample:\n```text\nfunction loggingIdentity<Type>(arg: Type): Type {  console.log(arg.length);Property 'length' does not exist on type 'Type'.2339Property 'length' does not exist on type 'Type'.  return arg;}\n```\n\nExample:\n```text\nfunction loggingIdentity<Type>(arg: Type[]): Type[] {  console.log(arg.length);  return arg;}\n```\n\nExample:\n```text\nfunction loggingIdentity<Type>(arg: Array<Type>): Array<Type> {  console.log(arg.length); // Array has a .length, so no more error  return arg;}\n```\n\nExample:\n```text\nfunction identity<Type>(arg: Type): Type {  return arg;} let myIdentity: <Type>(arg: Type) => Type = identity;\n```\n\nExample:\n```text\nfunction identity<Type>(arg: Type): Type {  return arg;} let myIdentity: <Input>(arg: Input) => Input = identity;\n```\n\nExample:\n```text\nfunction identity<Type>(arg: Type): Type {  return arg;} let myIdentity: { <Type>(arg: Type): Type } = identity;\n```\n\nExample:\n```text\ninterface GenericIdentityFn {  <Type>(arg: Type): Type;} function identity<Type>(arg: Type): Type {  return arg;} let myIdentity: GenericIdentityFn = identity;\n```\n\nExample:\n```text\ninterface GenericIdentityFn<Type> {  (arg: Type): Type;} function identity<Type>(arg: Type): Type {  return arg;} let myIdentity: GenericIdentityFn<number> = identity;\n```\n\nExample:\n```text\nclass GenericNumber<NumType> {  zeroValue: NumType;  add: (x: NumType, y: NumType) => NumType;} let myGenericNumber = new GenericNumber<number>();myGenericNumber.zeroValue = 0;myGenericNumber.add = function (x, y) {  return x + y;};\n```\n\nExample:\n```text\nlet stringNumeric = new GenericNumber<string>();stringNumeric.zeroValue = \"\";stringNumeric.add = function (x, y) {  return x + y;}; console.log(stringNumeric.add(stringNumeric.zeroValue, \"test\"));\n```\n\nExample:\n```text\ninterface Lengthwise {  length: number;} function loggingIdentity<Type extends Lengthwise>(arg: Type): Type {  console.log(arg.length); // Now we know it has a .length property, so no more error  return arg;}\n```\n\nExample:\n```text\nloggingIdentity(3);Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.2345Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.\n```\n\nExample:\n```text\nloggingIdentity({ length: 10, value: 3 });\n```\n\nExample:\n```text\nfunction getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {  return obj[key];} let x = { a: 1, b: 2, c: 3, d: 4 }; getProperty(x, \"a\");getProperty(x, \"m\");Argument of type '\"m\"' is not assignable to parameter of type '\"a\" | \"b\" | \"c\" | \"d\"'.2345Argument of type '\"m\"' is not assignable to parameter of type '\"a\" | \"b\" | \"c\" | \"d\"'.\n```\n\nExample:\n```text\nfunction create<Type>(c: { new (): Type }): Type {  return new c();}\n```\n\nExample:\n```text\nclass BeeKeeper {  hasMask: boolean = true;} class ZooKeeper {  nametag: string = \"Mikle\";} class Animal {  numLegs: number = 4;} class Bee extends Animal {  numLegs = 6;  keeper: BeeKeeper = new BeeKeeper();} class Lion extends Animal {  keeper: ZooKeeper = new ZooKeeper();} function createInstance<A extends Animal>(c: new () => A): A {  return new c();} createInstance(Lion).keeper.nametag;createInstance(Bee).keeper.hasMask;\n```\n\nExample:\n```text\ndeclare function create(): Container<HTMLDivElement, HTMLDivElement[]>;declare function create<T extends HTMLElement>(element: T): Container<T, T[]>;declare function create<T extends HTMLElement, U extends HTMLElement>(  element: T,  children: U[]): Container<T, U[]>;\n```\n\nExample:\n```text\ndeclare function create<T extends HTMLElement = HTMLDivElement, U extends HTMLElement[] = T[]>(  element?: T,  children?: U): Container<T, U>; const div = create();      const div: Container<HTMLDivElement, HTMLDivElement[]> const p = create(new HTMLParagraphElement());     const p: Container<HTMLParagraphElement, HTMLParagraphElement[]>\n```\n\nExample:\n```text\ninterface Producer<T> {  make(): T;}\n```\n\nExample:\n```text\ninterface Consumer<T> {  consume: (arg: T) => void;}\n```\n\nExample:\n```text\ninterface AnimalProducer {  make(): Animal;}// A CatProducer can be used anywhere an// Animal producer is expectedinterface CatProducer {  make(): Cat;}\n```\n\nExample:\n```text\n// Contravariant annotationinterface Consumer<in T> {  consume: (arg: T) => void;}// Covariant annotationinterface Producer<out T> {  make(): T;}// Invariant annotationinterface ProducerConsumer<in out T> {  consume: (arg: T) => void;  make(): T;}\n```\n\nExample:\n```text\n// DON'T DO THIS - variance annotation// does not match structural behaviorinterface Producer<in out T> {  make(): T;}// Not a type error -- this is a structural// comparison, so variance annotations are// not in effectconst p: Producer<string | number> = {    make(): number {        return 42;    }}\n```\n\nExample:\n```text\n// Error, this interface is definitely contravariant on Tinterface Foo<out T> {  consume: (arg: T) => void;}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.347Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":146,"estimatedTokens":1313}}13{"id":"doc-typescript_documentation_typescript_tooling_in_5-24add5b2","source":"documentation","title":"TypeScript: Documentation - TypeScript Tooling in 5 minutes","url":"https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html","text":"Example:\n```text\n> npm install -g typescript\n```\n\nExample:\n```text\nfunction greeter(person) {  return \"Hello, \" + person;} let user = \"Jane User\"; document.body.textContent = greeter(user);\n```\n\nExample:\n```text\ntsc greeter.ts\n```\n\nExample:\n```text\nfunction greeter(person: string) {  return \"Hello, \" + person;} let user = \"Jane User\"; document.body.textContent = greeter(user);\n```\n\nExample:\n```text\nfunction greeter(person: string) {  return \"Hello, \" + person;} let user = [0, 1, 2]; document.body.textContent = greeter(user);Argument of type 'number[]' is not assignable to parameter of type 'string'.2345Argument of type 'number[]' is not assignable to parameter of type 'string'.\n```\n\nExample:\n```text\nerror TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.\n```\n\nExample:\n```text\ninterface Person {  firstName: string;  lastName: string;} function greeter(person: Person) {  return \"Hello, \" + person.firstName + \" \" + person.lastName;} let user = { firstName: \"Jane\", lastName: \"User\" }; document.body.textContent = greeter(user);\n```\n\nExample:\n```text\nclass Student {  fullName: string;  constructor(    public firstName: string,    public middleInitial: string,    public lastName: string  ) {    this.fullName = firstName + \" \" + middleInitial + \" \" + lastName;  }} interface Person {  firstName: string;  lastName: string;} function greeter(person: Person) {  return \"Hello, \" + person.firstName + \" \" + person.lastName;} let user = new Student(\"Jane\", \"M.\", \"User\"); document.body.textContent = greeter(user);\n```\n\nExample:\n```text\n<!DOCTYPE html><html>  <head>    <title>TypeScript Greeter</title>  </head>  <body>    <script src=\"greeter.js\"></script>  </body></html>\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.347Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":46,"estimatedTokens":434}}14{"id":"doc-typescript_documentation_triple_slash_directives-d7d6a402","source":"documentation","title":"TypeScript: Documentation - Triple-Slash Directives","url":"https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html","text":"Example:\n```text\n/// <reference lib=\"es2017.string\" />\"foo\".padStart(4);\n```\n\nExample:\n```text\n/// <amd-module name=\"NamedModule\"/>export class C {}\n```\n\nExample:\n```text\ndefine(\"NamedModule\", [\"require\", \"exports\"], function (require, exports) {  var C = (function () {    function C() {}    return C;  })();  exports.C = C;});\n```\n\nExample:\n```text\n/// <amd-dependency path=\"legacy/moduleA\" name=\"moduleA\"/>declare var moduleA: MyType;moduleA.callStuff();\n```\n\nExample:\n```text\ndefine([\"require\", \"exports\", \"legacy/moduleA\"], function (  require,  exports,  moduleA) {  moduleA.callStuff();});\n```\n\nExample:\n```text\n/// <reference path=\"...\" />/// <reference types=\"...\" />/// <reference lib=\"...\" />\n```\n\nExample:\n```text\n/// <reference path=\"...\" preserve=\"true\" />/// <reference types=\"...\" preserve=\"true\" />/// <reference lib=\"...\" preserve=\"true\" />\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.348Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":36,"estimatedTokens":219}}15{"id":"doc-typescript_documentation_iterators_and_generator-0ee98785","source":"documentation","title":"TypeScript: Documentation - Iterators and Generators","url":"https://www.typescriptlang.org/docs/handbook/iterators-and-generators.html","text":"Example:\n```text\nfunction toArray<X>(xs: Iterable<X>): X[] {  return [...xs]}\n```\n\nExample:\n```text\nlet someArray = [1, \"string\", false];for (let entry of someArray) {  console.log(entry); // 1, \"string\", false}\n```\n\nExample:\n```text\nlet list = [4, 5, 6];for (let i in list) {  console.log(i); // \"0\", \"1\", \"2\",}for (let i of list) {  console.log(i); // 4, 5, 6}\n```\n\nExample:\n```text\nlet pets = new Set([\"Cat\", \"Dog\", \"Hamster\"]);pets[\"species\"] = \"mammals\";for (let pet in pets) {  console.log(pet); // \"species\"}for (let pet of pets) {  console.log(pet); // \"Cat\", \"Dog\", \"Hamster\"}\n```\n\nExample:\n```text\nlet numbers = [1, 2, 3];for (let num of numbers) {  console.log(num);}\n```\n\nExample:\n```text\nvar numbers = [1, 2, 3];for (var _i = 0; _i < numbers.length; _i++) {  var num = numbers[_i];  console.log(num);}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.348Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":31,"estimatedTokens":208}}16{"id":"doc-typescript_documentation_typescript_for_javascri-3fda319c","source":"documentation","title":"TypeScript: Documentation - TypeScript for JavaScript Programmers","url":"https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html","text":"Example:\n```text\nlet helloWorld = \"Hello World\";        let helloWorld: string\n```\n\nExample:\n```text\nconst user = {  name: \"Hayes\",  id: 0,};\n```\n\nExample:\n```text\ninterface User {  name: string;  id: number;}\n```\n\nExample:\n```text\nconst user: User = {  name: \"Hayes\",  id: 0,};\n```\n\nExample:\n```text\ninterface User {  name: string;  id: number;} const user: User = {  username: \"Hayes\",Object literal may only specify known properties, and 'username' does not exist in type 'User'.2353Object literal may only specify known properties, and 'username' does not exist in type 'User'.  id: 0,};\n```\n\nExample:\n```text\ninterface User {  name: string;  id: number;} class UserAccount {  name: string;  id: number;   constructor(name: string, id: number) {    this.name = name;    this.id = id;  }} const user: User = new UserAccount(\"Murphy\", 1);\n```\n\nExample:\n```text\nfunction deleteUser(user: User) {  // ...} function getAdminUser(): User {  //...}\n```\n\nExample:\n```text\ntype MyBool = true | false;\n```\n\nExample:\n```text\ntype WindowStates = \"open\" | \"closed\" | \"minimized\";type LockStates = \"locked\" | \"unlocked\";type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;\n```\n\nExample:\n```text\nfunction getLength(obj: string | string[]) {  return obj.length;}\n```\n\nExample:\n```text\nfunction wrapInArray(obj: string | string[]) {  if (typeof obj === \"string\") {    return [obj];            (parameter) obj: string  }  return obj;}\n```\n\nExample:\n```text\ntype StringArray = Array<string>;type NumberArray = Array<number>;type ObjectWithNameArray = Array<{ name: string }>;\n```\n\nExample:\n```text\ninterface Backpack<Type> {  add: (obj: Type) => void;  get: () => Type;} // This line is a shortcut to tell TypeScript there is a// constant called `backpack`, and to not worry about where it came from.declare const backpack: Backpack<string>; // object is a string, because we declared it above as the variable part of Backpack.const object = backpack.get(); // Since the backpack variable is a string, you can't pass a number to the add function.backpack.add(23);Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.\n```\n\nExample:\n```text\ninterface Point {  x: number;  y: number;} function logPoint(p: Point) {  console.log(`${p.x}, ${p.y}`);} // logs \"12, 26\"const point = { x: 12, y: 26 };logPoint(point);\n```\n\nExample:\n```text\nconst point3 = { x: 12, y: 26, z: 89 };logPoint(point3); // logs \"12, 26\" const rect = { x: 33, y: 3, width: 30, height: 80 };logPoint(rect); // logs \"33, 3\" const color = { hex: \"#187ABF\" };logPoint(color);Argument of type '{ hex: string; }' is not assignable to parameter of type 'Point'.\n  Type '{ hex: string; }' is missing the following properties from type 'Point': x, y2345Argument of type '{ hex: string; }' is not assignable to parameter of type 'Point'.\n  Type '{ hex: string; }' is missing the following properties from type 'Point': x, y\n```\n\nExample:\n```text\nclass VirtualPoint {  x: number;  y: number;   constructor(x: number, y: number) {    this.x = x;    this.y = y;  }} const newVPoint = new VirtualPoint(13, 56);logPoint(newVPoint); // logs \"13, 56\"\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.348Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":83,"estimatedTokens":801}}17{"id":"doc-typescript_documentation_object_types-e93a21d4","source":"documentation","title":"TypeScript: Documentation - Object Types","url":"https://www.typescriptlang.org/docs/handbook/2/objects.html","text":"Example:\n```text\nfunction greet(person: { name: string; age: number }) {  return \"Hello \" + person.name;}\n```\n\nExample:\n```text\ninterface Person {  name: string;  age: number;} function greet(person: Person) {  return \"Hello \" + person.name;}\n```\n\nExample:\n```text\ntype Person = {  name: string;  age: number;}; function greet(person: Person) {  return \"Hello \" + person.name;}\n```\n\nExample:\n```text\ninterface PaintOptions {  shape: Shape;  xPos?: number;  yPos?: number;} function paintShape(opts: PaintOptions) {  // ...} const shape = getShape();paintShape({ shape });paintShape({ shape, xPos: 100 });paintShape({ shape, yPos: 100 });paintShape({ shape, xPos: 100, yPos: 100 });\n```\n\nExample:\n```text\nfunction paintShape(opts: PaintOptions) {  let xPos = opts.xPos;                   (property) PaintOptions.xPos?: number | undefined  let yPos = opts.yPos;                   (property) PaintOptions.yPos?: number | undefined  // ...}\n```\n\nExample:\n```text\nfunction paintShape(opts: PaintOptions) {  let xPos = opts.xPos === undefined ? 0 : opts.xPos;       let xPos: number  let yPos = opts.yPos === undefined ? 0 : opts.yPos;       let yPos: number  // ...}\n```\n\nExample:\n```text\nfunction paintShape({ shape, xPos = 0, yPos = 0 }: PaintOptions) {  console.log(\"x coordinate at\", xPos);                                  (parameter) xPos: number  console.log(\"y coordinate at\", yPos);                                  (parameter) yPos: number  // ...}\n```\n\nExample:\n```text\nfunction draw({ shape: Shape, xPos: number = 100 /*...*/ }) {  render(shape);Cannot find name 'shape'. Did you mean 'Shape'?2552Cannot find name 'shape'. Did you mean 'Shape'?  render(xPos);Cannot find name 'xPos'.2304Cannot find name 'xPos'.}\n```\n\nExample:\n```text\ninterface SomeType {  readonly prop: string;} function doSomething(obj: SomeType) {  // We can read from 'obj.prop'.  console.log(`prop has the value '${obj.prop}'.`);   // But we can't re-assign it.  obj.prop = \"hello\";Cannot assign to 'prop' because it is a read-only property.2540Cannot assign to 'prop' because it is a read-only property.}\n```\n\nExample:\n```text\ninterface Home {  readonly resident: { name: string; age: number };} function visitForBirthday(home: Home) {  // We can read and update properties from 'home.resident'.  console.log(`Happy birthday ${home.resident.name}!`);  home.resident.age++;} function evict(home: Home) {  // But we can't write to the 'resident' property itself on a 'Home'.  home.resident = {Cannot assign to 'resident' because it is a read-only property.2540Cannot assign to 'resident' because it is a read-only property.    name: \"Victor the Evictor\",    age: 42,  };}\n```\n\nExample:\n```text\ninterface Person {  name: string;  age: number;} interface ReadonlyPerson {  readonly name: string;  readonly age: number;} let writablePerson: Person = {  name: \"Person McPersonface\",  age: 42,}; // workslet readonlyPerson: ReadonlyPerson = writablePerson; console.log(readonlyPerson.age); // prints '42'writablePerson.age++;console.log(readonlyPerson.age); // prints '43'\n```\n\nExample:\n```text\ninterface StringArray {  [index: number]: string;} const myArray: StringArray = getStringArray();const secondItem = myArray[1];          const secondItem: string\n```\n\nExample:\n```text\ninterface Animal {  name: string;} interface Dog extends Animal {  breed: string;} // Error: indexing with a numeric string might get you a completely separate type of Animal!interface NotOkay {  [x: number]: Animal;'number' index type 'Animal' is not assignable to 'string' index type 'Dog'.2413'number' index type 'Animal' is not assignable to 'string' index type 'Dog'.  [x: string]: Dog;}\n```\n\nExample:\n```text\ninterface NumberDictionary {  [index: string]: number;   length: number; // ok  name: string;Property 'name' of type 'string' is not assignable to 'string' index type 'number'.2411Property 'name' of type 'string' is not assignable to 'string' index type 'number'.}\n```\n\nExample:\n```text\ninterface NumberOrStringDictionary {  [index: string]: number | string;  length: number; // ok, length is a number  name: string; // ok, name is a string}\n```\n\nExample:\n```text\ninterface ReadonlyStringArray {  readonly [index: number]: string;} let myArray: ReadonlyStringArray = getReadOnlyStringArray();myArray[2] = \"Mallory\";Index signature in type 'ReadonlyStringArray' only permits reading.2542Index signature in type 'ReadonlyStringArray' only permits reading.\n```\n\nExample:\n```text\ninterface SquareConfig {  color?: string;  width?: number;} function createSquare(config: SquareConfig): { color: string; area: number } {  return {    color: config.color || \"red\",    area: config.width ? config.width * config.width : 20,  };} let mySquare = createSquare({ colour: \"red\", width: 100 });Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?2561Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?\n```\n\nExample:\n```text\nlet mySquare = createSquare({ colour: \"red\", width: 100 });Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?2561Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?\n```\n\nExample:\n```text\nlet mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);\n```\n\nExample:\n```text\ninterface SquareConfig {  color?: string;  width?: number;  [propName: string]: unknown;}\n```\n\nExample:\n```text\nlet squareOptions = { colour: \"red\", width: 100 };let mySquare = createSquare(squareOptions);\n```\n\nExample:\n```text\nlet squareOptions = { colour: \"red\" };let mySquare = createSquare(squareOptions);Type '{ colour: string; }' has no properties in common with type 'SquareConfig'.2559Type '{ colour: string; }' has no properties in common with type 'SquareConfig'.\n```\n\nExample:\n```text\ninterface BasicAddress {  name?: string;  street: string;  city: string;  country: string;  postalCode: string;}\n```\n\nExample:\n```text\ninterface AddressWithUnit {  name?: string;  unit: string;  street: string;  city: string;  country: string;  postalCode: string;}\n```\n\nExample:\n```text\ninterface BasicAddress {  name?: string;  street: string;  city: string;  country: string;  postalCode: string;} interface AddressWithUnit extends BasicAddress {  unit: string;}\n```\n\nExample:\n```text\ninterface Colorful {  color: string;} interface Circle {  radius: number;} interface ColorfulCircle extends Colorful, Circle {} const cc: ColorfulCircle = {  color: \"red\",  radius: 42,};\n```\n\nExample:\n```text\ninterface Colorful {  color: string;}interface Circle {  radius: number;} type ColorfulCircle = Colorful & Circle;\n```\n\nExample:\n```text\nfunction draw(circle: Colorful & Circle) {  console.log(`Color was ${circle.color}`);  console.log(`Radius was ${circle.radius}`);} // okaydraw({ color: \"blue\", radius: 42 }); // oopsdraw({ color: \"red\", raidus: 42 });Object literal may only specify known properties, but 'raidus' does not exist in type 'Colorful & Circle'. Did you mean to write 'radius'?2561Object literal may only specify known properties, but 'raidus' does not exist in type 'Colorful & Circle'. Did you mean to write 'radius'?\n```\n\nExample:\n```text\ninterface Person {  name: string;}interface Person {  name: number;}\n```\n\nExample:\n```text\ninterface Person1 {  name: string;} interface Person2 {  name: number;} type Staff = Person1 & Person2 declare const staffer: Staff;staffer.name;         (property) name: never\n```\n\nExample:\n```text\ninterface Box {  contents: any;}\n```\n\nExample:\n```text\ninterface Box {  contents: unknown;} let x: Box = {  contents: \"hello world\",}; // we could check 'x.contents'if (typeof x.contents === \"string\") {  console.log(x.contents.toLowerCase());} // or we could use a type assertionconsole.log((x.contents as string).toLowerCase());\n```\n\nExample:\n```text\ninterface NumberBox {  contents: number;} interface StringBox {  contents: string;} interface BooleanBox {  contents: boolean;}\n```\n\nExample:\n```text\nfunction setContents(box: StringBox, newContents: string): void;function setContents(box: NumberBox, newContents: number): void;function setContents(box: BooleanBox, newContents: boolean): void;function setContents(box: { contents: any }, newContents: any) {  box.contents = newContents;}\n```\n\nExample:\n```text\ninterface Box<Type> {  contents: Type;}\n```\n\nExample:\n```text\nlet box: Box<string>;\n```\n\nExample:\n```text\ninterface Box<Type> {  contents: Type;}interface StringBox {  contents: string;} let boxA: Box<string> = { contents: \"hello\" };boxA.contents;        (property) Box<string>.contents: string let boxB: StringBox = { contents: \"world\" };boxB.contents;        (property) StringBox.contents: string\n```\n\nExample:\n```text\ninterface Box<Type> {  contents: Type;} interface Apple {  // ....} // Same as '{ contents: Apple }'.type AppleBox = Box<Apple>;\n```\n\nExample:\n```text\nfunction setContents<Type>(box: Box<Type>, newContents: Type) {  box.contents = newContents;}\n```\n\nExample:\n```text\ntype Box<Type> = {  contents: Type;};\n```\n\nExample:\n```text\ntype OrNull<Type> = Type | null; type OneOrMany<Type> = Type | Type[]; type OneOrManyOrNull<Type> = OrNull<OneOrMany<Type>>;           type OneOrManyOrNull<Type> = OneOrMany<Type> | null type OneOrManyOrNullStrings = OneOrManyOrNull<string>;               type OneOrManyOrNullStrings = OneOrMany<string> | null\n```\n\nExample:\n```text\nfunction doSomething(value: Array<string>) {  // ...} let myArray: string[] = [\"hello\", \"world\"]; // either of these work!doSomething(myArray);doSomething(new Array(\"hello\", \"world\"));\n```\n\nExample:\n```text\ninterface Array<Type> {  /**   * Gets or sets the length of the array.   */  length: number;   /**   * Removes the last element from an array and returns it.   */  pop(): Type | undefined;   /**   * Appends new elements to an array, and returns the new length of the array.   */  push(...items: Type[]): number;   // ...}\n```\n\nExample:\n```text\nfunction doStuff(values: ReadonlyArray<string>) {  // We can read from 'values'...  const copy = values.slice();  console.log(`The first value is ${values[0]}`);   // ...but we can't mutate 'values'.  values.push(\"hello!\");Property 'push' does not exist on type 'readonly string[]'.2339Property 'push' does not exist on type 'readonly string[]'.}\n```\n\nExample:\n```text\nnew ReadonlyArray(\"red\", \"green\", \"blue\");'ReadonlyArray' only refers to a type, but is being used as a value here.2693'ReadonlyArray' only refers to a type, but is being used as a value here.\n```\n\nExample:\n```text\nconst roArray: ReadonlyArray<string> = [\"red\", \"green\", \"blue\"];\n```\n\nExample:\n```text\nfunction doStuff(values: readonly string[]) {  // We can read from 'values'...  const copy = values.slice();  console.log(`The first value is ${values[0]}`);   // ...but we can't mutate 'values'.  values.push(\"hello!\");Property 'push' does not exist on type 'readonly string[]'.2339Property 'push' does not exist on type 'readonly string[]'.}\n```\n\nExample:\n```text\nlet x: readonly string[] = [];let y: string[] = []; x = y;y = x;The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.4104The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.\n```\n\nExample:\n```text\ntype StringNumberPair = [string, number];\n```\n\nExample:\n```text\nfunction doSomething(pair: [string, number]) {  const a = pair[0];       const a: string  const b = pair[1];       const b: number  // ...} doSomething([\"hello\", 42]);\n```\n\nExample:\n```text\nfunction doSomething(pair: [string, number]) {  // ...   const c = pair[2];Tuple type '[string, number]' of length '2' has no element at index '2'.2493Tuple type '[string, number]' of length '2' has no element at index '2'.}\n```\n\nExample:\n```text\nfunction doSomething(stringHash: [string, number]) {  const [inputString, hash] = stringHash;   console.log(inputString);                  const inputString: string   console.log(hash);               const hash: number}\n```\n\nExample:\n```text\ninterface StringNumberPair {  // specialized properties  length: 2;  0: string;  1: number;   // Other 'Array<string | number>' members...  slice(start?: number, end?: number): Array<string | number>;}\n```\n\nExample:\n```text\ntype Either2dOr3d = [number, number, number?]; function setCoordinate(coord: Either2dOr3d) {  const [x, y, z] = coord;              const z: number | undefined   console.log(`Provided coordinates had ${coord.length} dimensions`);                                                  (property) length: 2 | 3}\n```\n\nExample:\n```text\ntype StringNumberBooleans = [string, number, ...boolean[]];type StringBooleansNumber = [string, ...boolean[], number];type BooleansStringNumber = [...boolean[], string, number];\n```\n\nExample:\n```text\nconst a: StringNumberBooleans = [\"hello\", 1];const b: StringNumberBooleans = [\"beautiful\", 2, true];const c: StringNumberBooleans = [\"world\", 3, true, false, true, false, true];\n```\n\nExample:\n```text\nfunction readButtonInput(...args: [string, number, ...boolean[]]) {  const [name, version, ...input] = args;  // ...}\n```\n\nExample:\n```text\nfunction readButtonInput(name: string, version: number, ...input: boolean[]) {  // ...}\n```\n\nExample:\n```text\nfunction doSomething(pair: readonly [string, number]) {  // ...}\n```\n\nExample:\n```text\nfunction doSomething(pair: readonly [string, number]) {  pair[0] = \"hello!\";Cannot assign to '0' because it is a read-only property.2540Cannot assign to '0' because it is a read-only property.}\n```\n\nExample:\n```text\nlet point = [3, 4] as const; function distanceFromOrigin([x, y]: [number, number]) {  return Math.sqrt(x ** 2 + y ** 2);} distanceFromOrigin(point);Argument of type 'readonly [3, 4]' is not assignable to parameter of type '[number, number]'.\n  The type 'readonly [3, 4]' is 'readonly' and cannot be assigned to the mutable type '[number, number]'.2345Argument of type 'readonly [3, 4]' is not assignable to parameter of type '[number, number]'.\n  The type 'readonly [3, 4]' is 'readonly' and cannot be assigned to the mutable type '[number, number]'.\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.350Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":61,"totalLines":308,"estimatedTokens":3552}}18{"id":"doc-typescript_documentation_symbols-ee054e68","source":"documentation","title":"TypeScript: Documentation - Symbols","url":"https://www.typescriptlang.org/docs/handbook/symbols.html","text":"Example:\n```text\nlet sym1 = Symbol();let sym2 = Symbol(\"key\"); // optional string key\n```\n\nExample:\n```text\nlet sym2 = Symbol(\"key\");let sym3 = Symbol(\"key\");sym2 === sym3; // false, symbols are unique\n```\n\nExample:\n```text\nconst sym = Symbol();let obj = {  [sym]: \"value\",};console.log(obj[sym]); // \"value\"\n```\n\nExample:\n```text\nconst getClassNameSymbol = Symbol();class C {  [getClassNameSymbol]() {    return \"C\";  }}let c = new C();let className = c[getClassNameSymbol](); // \"C\"\n```\n\nExample:\n```text\ndeclare const sym1: unique symbol; // sym2 can only be a constant reference.let sym2: unique symbol = Symbol();A variable whose type is a 'unique symbol' type must be 'const'.1332A variable whose type is a 'unique symbol' type must be 'const'. // Works - refers to a unique symbol, but its identity is tied to 'sym1'.let sym3: typeof sym1 = sym1; // Also works.class C {  static readonly StaticSymbol: unique symbol = Symbol();}\n```\n\nExample:\n```text\nconst sym2 = Symbol();const sym3 = Symbol(); if (sym2 === sym3) {This comparison appears to be unintentional because the types 'typeof sym2' and 'typeof sym3' have no overlap.2367This comparison appears to be unintentional because the types 'typeof sym2' and 'typeof sym3' have no overlap.  // ...}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.350Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":31,"estimatedTokens":319}}19{"id":"doc-typescript_documentation_namespaces-82147dc0","source":"documentation","title":"TypeScript: Documentation - Namespaces","url":"https://www.typescriptlang.org/docs/handbook/namespaces.html","text":"Example:\n```text\ninterface StringValidator {  isAcceptable(s: string): boolean;}let lettersRegexp = /^[A-Za-z]+$/;let numberRegexp = /^[0-9]+$/;class LettersOnlyValidator implements StringValidator {  isAcceptable(s: string) {    return lettersRegexp.test(s);  }}class ZipCodeValidator implements StringValidator {  isAcceptable(s: string) {    return s.length === 5 && numberRegexp.test(s);  }}// Some samples to trylet strings = [\"Hello\", \"98052\", \"101\"];// Validators to uselet validators: { [s: string]: StringValidator } = {};validators[\"ZIP code\"] = new ZipCodeValidator();validators[\"Letters only\"] = new LettersOnlyValidator();// Show whether each string passed each validatorfor (let s of strings) {  for (let name in validators) {    let isMatch = validators[name].isAcceptable(s);    console.log(`'${s}' ${isMatch ? \"matches\" : \"does not match\"} '${name}'.`);  }}\n```\n\nExample:\n```text\nnamespace Validation {  export interface StringValidator {    isAcceptable(s: string): boolean;  }  const lettersRegexp = /^[A-Za-z]+$/;  const numberRegexp = /^[0-9]+$/;  export class LettersOnlyValidator implements StringValidator {    isAcceptable(s: string) {      return lettersRegexp.test(s);    }  }  export class ZipCodeValidator implements StringValidator {    isAcceptable(s: string) {      return s.length === 5 && numberRegexp.test(s);    }  }}// Some samples to trylet strings = [\"Hello\", \"98052\", \"101\"];// Validators to uselet validators: { [s: string]: Validation.StringValidator } = {};validators[\"ZIP code\"] = new Validation.ZipCodeValidator();validators[\"Letters only\"] = new Validation.LettersOnlyValidator();// Show whether each string passed each validatorfor (let s of strings) {  for (let name in validators) {    console.log(      `\"${s}\" - ${        validators[name].isAcceptable(s) ? \"matches\" : \"does not match\"      } ${name}`    );  }}\n```\n\nExample:\n```text\nnamespace Validation {  export interface StringValidator {    isAcceptable(s: string): boolean;  }}\n```\n\nExample:\n```text\n/// <reference path=\"Validation.ts\" />namespace Validation {  const lettersRegexp = /^[A-Za-z]+$/;  export class LettersOnlyValidator implements StringValidator {    isAcceptable(s: string) {      return lettersRegexp.test(s);    }  }}\n```\n\nExample:\n```text\n/// <reference path=\"Validation.ts\" />namespace Validation {  const numberRegexp = /^[0-9]+$/;  export class ZipCodeValidator implements StringValidator {    isAcceptable(s: string) {      return s.length === 5 && numberRegexp.test(s);    }  }}\n```\n\nExample:\n```text\n/// <reference path=\"Validation.ts\" />/// <reference path=\"LettersOnlyValidator.ts\" />/// <reference path=\"ZipCodeValidator.ts\" />// Some samples to trylet strings = [\"Hello\", \"98052\", \"101\"];// Validators to uselet validators: { [s: string]: Validation.StringValidator } = {};validators[\"ZIP code\"] = new Validation.ZipCodeValidator();validators[\"Letters only\"] = new Validation.LettersOnlyValidator();// Show whether each string passed each validatorfor (let s of strings) {  for (let name in validators) {    console.log(      `\"${s}\" - ${        validators[name].isAcceptable(s) ? \"matches\" : \"does not match\"      } ${name}`    );  }}\n```\n\nExample:\n```text\ntsc --outFile sample.js Test.ts\n```\n\nExample:\n```text\ntsc --outFile sample.js Validation.ts LettersOnlyValidator.ts ZipCodeValidator.ts Test.ts\n```\n\nExample:\n```text\n<script src=\"Validation.js\" type=\"text/javascript\" /><script src=\"LettersOnlyValidator.js\" type=\"text/javascript\" /><script src=\"ZipCodeValidator.js\" type=\"text/javascript\" /><script src=\"Test.js\" type=\"text/javascript\" />\n```\n\nExample:\n```text\nnamespace Shapes {  export namespace Polygons {    export class Triangle {}    export class Square {}  }}import polygons = Shapes.Polygons;let sq = new polygons.Square(); // Same as 'new Shapes.Polygons.Square()'\n```\n\nExample:\n```text\ndeclare namespace D3 {  export interface Selectors {    select: {      (selector: string): Selection;      (element: EventTarget): Selection;    };  }  export interface Event {    x: number;    y: number;  }  export interface Base extends Selectors {    event: Event;  }}declare var d3: D3.Base;\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.351Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":56,"estimatedTokens":1039}}20{"id":"doc-typescript_documentation_conditional_types-27e2f7bd","source":"documentation","title":"TypeScript: Documentation - Conditional Types","url":"https://www.typescriptlang.org/docs/handbook/2/conditional-types.html","text":"Example:\n```text\ninterface Animal {  live(): void;}interface Dog extends Animal {  woof(): void;} type Example1 = Dog extends Animal ? number : string;        type Example1 = number type Example2 = RegExp extends Animal ? number : string;        type Example2 = string\n```\n\nExample:\n```text\nSomeType extends OtherType ? TrueType : FalseType;\n```\n\nExample:\n```text\ninterface IdLabel {  id: number /* some fields */;}interface NameLabel {  name: string /* other fields */;} function createLabel(id: number): IdLabel;function createLabel(name: string): NameLabel;function createLabel(nameOrId: string | number): IdLabel | NameLabel;function createLabel(nameOrId: string | number): IdLabel | NameLabel {  throw \"unimplemented\";}\n```\n\nExample:\n```text\ntype NameOrId<T extends number | string> = T extends number  ? IdLabel  : NameLabel;\n```\n\nExample:\n```text\nfunction createLabel<T extends number | string>(idOrName: T): NameOrId<T> {  throw \"unimplemented\";} let a = createLabel(\"typescript\");   let a: NameLabel let b = createLabel(2.8);   let b: IdLabel let c = createLabel(Math.random() ? \"hello\" : 42);let c: NameLabel | IdLabel\n```\n\nExample:\n```text\ntype MessageOf<T> = T[\"message\"];Type '\"message\"' cannot be used to index type 'T'.2536Type '\"message\"' cannot be used to index type 'T'.\n```\n\nExample:\n```text\ntype MessageOf<T extends { message: unknown }> = T[\"message\"]; interface Email {  message: string;} type EmailMessageContents = MessageOf<Email>;              type EmailMessageContents = string\n```\n\nExample:\n```text\ntype MessageOf<T> = T extends { message: unknown } ? T[\"message\"] : never; interface Email {  message: string;} interface Dog {  bark(): void;} type EmailMessageContents = MessageOf<Email>;              type EmailMessageContents = string type DogMessageContents = MessageOf<Dog>;             type DogMessageContents = never\n```\n\nExample:\n```text\ntype Flatten<T> = T extends any[] ? T[number] : T; // Extracts out the element type.type Str = Flatten<string[]>;     type Str = string // Leaves the type alone.type Num = Flatten<number>;     type Num = number\n```\n\nExample:\n```text\ntype Flatten<Type> = Type extends Array<infer Item> ? Item : Type;\n```\n\nExample:\n```text\ntype GetReturnType<Type> = Type extends (...args: never[]) => infer Return  ? Return  : never; type Num = GetReturnType<() => number>;     type Num = number type Str = GetReturnType<(x: string) => string>;     type Str = string type Bools = GetReturnType<(a: boolean, b: boolean) => boolean[]>;      type Bools = boolean[]\n```\n\nExample:\n```text\ndeclare function stringOrNum(x: string): number;declare function stringOrNum(x: number): string;declare function stringOrNum(x: string | number): string | number; type T1 = ReturnType<typeof stringOrNum>;     type T1 = string | number\n```\n\nExample:\n```text\ntype ToArray<Type> = Type extends any ? Type[] : never;\n```\n\nExample:\n```text\ntype ToArray<Type> = Type extends any ? Type[] : never; type StrArrOrNumArr = ToArray<string | number>;           type StrArrOrNumArr = string[] | number[]\n```\n\nExample:\n```text\nstring | number;\n```\n\nExample:\n```text\nToArray<string> | ToArray<number>;\n```\n\nExample:\n```text\nstring[] | number[];\n```\n\nExample:\n```text\ntype ToArrayNonDist<Type> = [Type] extends [any] ? Type[] : never; // 'ArrOfStrOrNum' is no longer a union.type ArrOfStrOrNum = ToArrayNonDist<string | number>;          type ArrOfStrOrNum = (string | number)[]\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.351Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":91,"estimatedTokens":855}}21{"id":"doc-typescript_documentation_declaration_merging-4d18f3bf","source":"documentation","title":"TypeScript: Documentation - Declaration Merging","url":"https://www.typescriptlang.org/docs/handbook/declaration-merging.html","text":"Example:\n```text\ninterface Box {  height: number;  width: number;}interface Box {  scale: number;}let box: Box = { height: 5, width: 6, scale: 10 };\n```\n\nExample:\n```text\ninterface Cloner {  clone(animal: Animal): Animal;}interface Cloner {  clone(animal: Sheep): Sheep;}interface Cloner {  clone(animal: Dog): Dog;  clone(animal: Cat): Cat;}\n```\n\nExample:\n```text\ninterface Cloner {  clone(animal: Dog): Dog;  clone(animal: Cat): Cat;  clone(animal: Sheep): Sheep;  clone(animal: Animal): Animal;}\n```\n\nExample:\n```text\ninterface Document {  createElement(tagName: any): Element;}interface Document {  createElement(tagName: \"div\"): HTMLDivElement;  createElement(tagName: \"span\"): HTMLSpanElement;}interface Document {  createElement(tagName: string): HTMLElement;  createElement(tagName: \"canvas\"): HTMLCanvasElement;}\n```\n\nExample:\n```text\ninterface Document {  createElement(tagName: \"canvas\"): HTMLCanvasElement;  createElement(tagName: \"div\"): HTMLDivElement;  createElement(tagName: \"span\"): HTMLSpanElement;  createElement(tagName: string): HTMLElement;  createElement(tagName: any): Element;}\n```\n\nExample:\n```text\nnamespace Animals {  export class Zebra {}}namespace Animals {  export interface Legged {    numberOfLegs: number;  }  export class Dog {}}\n```\n\nExample:\n```text\nnamespace Animals {  export interface Legged {    numberOfLegs: number;  }  export class Zebra {}  export class Dog {}}\n```\n\nExample:\n```text\nnamespace Animal {  let haveMuscles = true;  export function animalsHaveMuscles() {    return haveMuscles;  }}namespace Animal {  export function doAnimalsHaveMuscles() {    return haveMuscles; // Error, because haveMuscles is not accessible here  }}\n```\n\nExample:\n```text\nclass Album {  label: Album.AlbumLabel;}namespace Album {  export class AlbumLabel {}}\n```\n\nExample:\n```text\nfunction buildLabel(name: string): string {  return buildLabel.prefix + name + buildLabel.suffix;}namespace buildLabel {  export let suffix = \"\";  export let prefix = \"Hello, \";}console.log(buildLabel(\"Sam Smith\"));\n```\n\nExample:\n```text\nenum Color {  red = 1,  green = 2,  blue = 4,}namespace Color {  export function mixColor(colorName: string) {    if (colorName == \"yellow\") {      return Color.red + Color.green;    } else if (colorName == \"white\") {      return Color.red + Color.green + Color.blue;    } else if (colorName == \"magenta\") {      return Color.red + Color.blue;    } else if (colorName == \"cyan\") {      return Color.green + Color.blue;    }  }}\n```\n\nExample:\n```text\n// observable.tsexport class Observable<T> {  // ... implementation left as an exercise for the reader ...}// map.tsimport { Observable } from \"./observable\";Observable.prototype.map = function (f) {  // ... another exercise for the reader};\n```\n\nExample:\n```text\n// observable.tsexport class Observable<T> {  // ... implementation left as an exercise for the reader ...}// map.tsimport { Observable } from \"./observable\";declare module \"./observable\" {  interface Observable<T> {    map<U>(f: (x: T) => U): Observable<U>;  }}Observable.prototype.map = function (f) {  // ... another exercise for the reader};// consumer.tsimport { Observable } from \"./observable\";import \"./map\";let o: Observable<number>;o.map((x) => x.toFixed());\n```\n\nExample:\n```text\n// observable.tsexport class Observable<T> {  // ... still no implementation ...}declare global {  interface Array<T> {    toObservable(): Observable<T>;  }}Array.prototype.toObservable = function () {  // ...};\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.352Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":71,"estimatedTokens":871}}22{"id":"doc-typescript_documentation_template_literal_types-b0244674","source":"documentation","title":"TypeScript: Documentation - Template Literal Types","url":"https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html","text":"Example:\n```text\ntype World = \"world\"; type Greeting = `hello ${World}`;        type Greeting = \"hello world\"\n```\n\nExample:\n```text\ntype EmailLocaleIDs = \"welcome_email\" | \"email_heading\";type FooterLocaleIDs = \"footer_title\" | \"footer_sendoff\"; type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;          type AllLocaleIDs = \"welcome_email_id\" | \"email_heading_id\" | \"footer_title_id\" | \"footer_sendoff_id\"\n```\n\nExample:\n```text\ntype AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;type Lang = \"en\" | \"ja\" | \"pt\"; type LocaleMessageIDs = `${Lang}_${AllLocaleIDs}`;            type LocaleMessageIDs = \"en_welcome_email_id\" | \"en_email_heading_id\" | \"en_footer_title_id\" | \"en_footer_sendoff_id\" | \"ja_welcome_email_id\" | \"ja_email_heading_id\" | \"ja_footer_title_id\" | \"ja_footer_sendoff_id\" | \"pt_welcome_email_id\" | \"pt_email_heading_id\" | \"pt_footer_title_id\" | \"pt_footer_sendoff_id\"\n```\n\nExample:\n```text\nconst passedObject = {  firstName: \"Saoirse\",  lastName: \"Ronan\",  age: 26,};\n```\n\nExample:\n```text\nconst person = makeWatchedObject({  firstName: \"Saoirse\",  lastName: \"Ronan\",  age: 26,}); // makeWatchedObject has added `on` to the anonymous Object person.on(\"firstNameChanged\", (newValue) => {  console.log(`firstName was changed to ${newValue}!`);});\n```\n\nExample:\n```text\ntype PropEventSource<Type> = {    on(eventName: `${string & keyof Type}Changed`, callback: (newValue: any) => void): void;}; /// Create a \"watched object\" with an `on` method/// so that you can watch for changes to properties.declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;\n```\n\nExample:\n```text\nconst person = makeWatchedObject({  firstName: \"Saoirse\",  lastName: \"Ronan\",  age: 26}); person.on(\"firstNameChanged\", () => {}); // Prevent easy human error (using the key instead of the event name)person.on(\"firstName\", () => {});Argument of type '\"firstName\"' is not assignable to parameter of type '\"firstNameChanged\" | \"lastNameChanged\" | \"ageChanged\"'.2345Argument of type '\"firstName\"' is not assignable to parameter of type '\"firstNameChanged\" | \"lastNameChanged\" | \"ageChanged\"'. // It's typo-resistantperson.on(\"frstNameChanged\", () => {});Argument of type '\"frstNameChanged\"' is not assignable to parameter of type '\"firstNameChanged\" | \"lastNameChanged\" | \"ageChanged\"'.2345Argument of type '\"frstNameChanged\"' is not assignable to parameter of type '\"firstNameChanged\" | \"lastNameChanged\" | \"ageChanged\"'.\n```\n\nExample:\n```text\ntype PropEventSource<Type> = {    on<Key extends string & keyof Type>        (eventName: `${Key}Changed`, callback: (newValue: Type[Key]) => void): void;}; declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>; const person = makeWatchedObject({  firstName: \"Saoirse\",  lastName: \"Ronan\",  age: 26}); person.on(\"firstNameChanged\", newName => {                                (parameter) newName: string    console.log(`new name is ${newName.toUpperCase()}`);}); person.on(\"ageChanged\", newAge => {                          (parameter) newAge: number    if (newAge < 0) {        console.warn(\"warning! negative age\");    }})\n```\n\nExample:\n```text\ntype Greeting = \"Hello, world\"type ShoutyGreeting = Uppercase<Greeting>           type ShoutyGreeting = \"HELLO, WORLD\" type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`type MainID = ASCIICacheKey<\"my_app\">       type MainID = \"ID-MY_APP\"\n```\n\nExample:\n```text\ntype Greeting = \"Hello, world\"type QuietGreeting = Lowercase<Greeting>          type QuietGreeting = \"hello, world\" type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`type MainID = ASCIICacheKey<\"MY_APP\">       type MainID = \"id-my_app\"\n```\n\nExample:\n```text\ntype LowercaseGreeting = \"hello, world\";type Greeting = Capitalize<LowercaseGreeting>;        type Greeting = \"Hello, world\"\n```\n\nExample:\n```text\ntype UppercaseGreeting = \"HELLO WORLD\";type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>;              type UncomfortableGreeting = \"hELLO WORLD\"\n```\n\nExample:\n```text\nfunction applyStringMapping(symbol: Symbol, str: string) {\n    switch (intrinsicTypeKinds.get(symbol.escapedName as string)) {\n        case IntrinsicTypeKind.Uppercase: return str.toUpperCase();\n        case IntrinsicTypeKind.Lowercase: return str.toLowerCase();\n        case IntrinsicTypeKind.Capitalize: return str.charAt(0).toUpperCase() + str.slice(1);\n        case IntrinsicTypeKind.Uncapitalize: return str.charAt(0).toLowerCase() + str.slice(1);\n    }\n    return str;\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.352Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":74,"estimatedTokens":1130}}23{"id":"doc-typescript_documentation_mixins-a4ed299b","source":"documentation","title":"TypeScript: Documentation - Mixins","url":"https://www.typescriptlang.org/docs/handbook/mixins.html","text":"Example:\n```text\nclass Sprite {  name = \"\";  x = 0;  y = 0;   constructor(name: string) {    this.name = name;  }}\n```\n\nExample:\n```text\n// To get started, we need a type which we'll use to extend// other classes from. The main responsibility is to declare// that the type being passed in is a class. type Constructor = new (...args: any[]) => {}; // This mixin adds a scale property, with getters and setters// for changing it with an encapsulated private property: function Scale<TBase extends Constructor>(Base: TBase) {  return class Scaling extends Base {    // Mixins may not declare private/protected properties    // however, you can use ES2020 private fields    _scale = 1;     setScale(scale: number) {      this._scale = scale;    }     get scale(): number {      return this._scale;    }  };}\n```\n\nExample:\n```text\n// Compose a new class from the Sprite class,// with the Mixin Scale applier:const EightBitSprite = Scale(Sprite); const flappySprite = new EightBitSprite(\"Bird\");flappySprite.setScale(0.8);console.log(flappySprite.scale);\n```\n\nExample:\n```text\n// This was our previous constructor:type Constructor = new (...args: any[]) => {};// Now we use a generic version which can apply a constraint on// the class which this mixin is applied totype GConstructor<T = {}> = new (...args: any[]) => T;\n```\n\nExample:\n```text\ntype Positionable = GConstructor<{ setPos: (x: number, y: number) => void }>;type Spritable = GConstructor<Sprite>;type Loggable = GConstructor<{ print: () => void }>;\n```\n\nExample:\n```text\nfunction Jumpable<TBase extends Positionable>(Base: TBase) {  return class Jumpable extends Base {    jump() {      // This mixin will only work if it is passed a base      // class which has setPos defined because of the      // Positionable constraint.      this.setPos(0, 20);    }  };}\n```\n\nExample:\n```text\n// Each mixin is a traditional ES classclass Jumpable {  jump() {}} class Duckable {  duck() {}} // Including the baseclass Sprite {  x = 0;  y = 0;} // Then you create an interface which merges// the expected mixins with the same name as your baseinterface Sprite extends Jumpable, Duckable {}// Apply the mixins into the base class via// the JS at runtimeapplyMixins(Sprite, [Jumpable, Duckable]); let player = new Sprite();player.jump();console.log(player.x, player.y); // This can live anywhere in your codebase:function applyMixins(derivedCtor: any, constructors: any[]) {  constructors.forEach((baseCtor) => {    Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {      Object.defineProperty(        derivedCtor.prototype,        name,        Object.getOwnPropertyDescriptor(baseCtor.prototype, name) ||          Object.create(null)      );    });  });}\n```\n\nExample:\n```text\n// A decorator function which replicates the mixin pattern:const Pausable = (target: typeof Player) => {  return class Pausable extends target {    shouldFreeze = false;  };}; @Pausableclass Player {  x = 0;  y = 0;} // The Player class does not have the decorator's type merged:const player = new Player();player.shouldFreeze;Property 'shouldFreeze' does not exist on type 'Player'.2339Property 'shouldFreeze' does not exist on type 'Player'. // The runtime aspect could be manually replicated via// type composition or interface merging.type FreezablePlayer = Player & { shouldFreeze: boolean }; const playerTwo = (new Player() as unknown) as FreezablePlayer;playerTwo.shouldFreeze;\n```\n\nExample:\n```text\nfunction base<T>() {  class Base {    static prop: T;  }  return Base;} function derived<T>() {  class Derived extends base<T>() {    static anotherProp: T;  }  return Derived;} class Spec extends derived<string>() {} Spec.prop; // stringSpec.anotherProp; // string\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.353Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":46,"estimatedTokens":932}}24{"id":"doc-typescript_documentation_modules-6d20303f","source":"documentation","title":"TypeScript: Documentation - Modules","url":"https://www.typescriptlang.org/docs/handbook/2/modules.html","text":"Example:\n```text\nexport {};\n```\n\nExample:\n```text\n// @filename: hello.tsexport default function helloWorld() {  console.log(\"Hello, world!\");}\n```\n\nExample:\n```text\nimport helloWorld from \"./hello.js\";helloWorld();\n```\n\nExample:\n```text\n// @filename: maths.tsexport var pi = 3.14;export let squareTwo = 1.41;export const phi = 1.61; export class RandomNumberGenerator {} export function absolute(num: number) {  if (num < 0) return num * -1;  return num;}\n```\n\nExample:\n```text\nimport { pi, phi, absolute } from \"./maths.js\"; console.log(pi);const absPhi = absolute(phi);        const absPhi: number\n```\n\nExample:\n```text\nimport { pi as π } from \"./maths.js\"; console.log(π);           (alias) var π: number\nimport π\n```\n\nExample:\n```text\n// @filename: maths.tsexport const pi = 3.14;export default class RandomNumberGenerator {} // @filename: app.tsimport RandomNumberGenerator, { pi as π } from \"./maths.js\"; RandomNumberGenerator;         (alias) class RandomNumberGenerator\nimport RandomNumberGenerator console.log(π);           (alias) const π: 3.14\nimport π\n```\n\nExample:\n```text\n// @filename: app.tsimport * as math from \"./maths.js\"; console.log(math.pi);const positivePhi = math.absolute(math.phi);          const positivePhi: number\n```\n\nExample:\n```text\n// @filename: app.tsimport \"./maths.js\"; console.log(\"3.14\");\n```\n\nExample:\n```text\n// @filename: animal.tsexport type Cat = { breed: string; yearOfBirth: number }; export interface Dog {  breeds: string[];  yearOfBirth: number;} // @filename: app.tsimport { Cat, Dog } from \"./animal.js\";type Animals = Cat | Dog;\n```\n\nExample:\n```text\n// @filename: animal.tsexport type Cat = { breed: string; yearOfBirth: number };export type Dog = { breeds: string[]; yearOfBirth: number };export const createCatName = () => \"fluffy\"; // @filename: valid.tsimport type { Cat, Dog } from \"./animal.js\";export type Animals = Cat | Dog; // @filename: app.tsimport type { createCatName } from \"./animal.js\";const name = createCatName();'createCatName' cannot be used as a value because it was imported using 'import type'.1361'createCatName' cannot be used as a value because it was imported using 'import type'.\n```\n\nExample:\n```text\n// @filename: app.tsimport { createCatName, type Cat, type Dog } from \"./animal.js\"; export type Animals = Cat | Dog;const name = createCatName();\n```\n\nExample:\n```text\nimport fs = require(\"fs\");const code = fs.readFileSync(\"hello.ts\", \"utf8\");\n```\n\nExample:\n```text\nfunction absolute(num: number) {  if (num < 0) return num * -1;  return num;} module.exports = {  pi: 3.14,  squareTwo: 1.41,  phi: 1.61,  absolute,};\n```\n\nExample:\n```text\nconst maths = require(\"./maths\");maths.pi;      any\n```\n\nExample:\n```text\nconst { squareTwo } = require(\"./maths\");squareTwo;   const squareTwo: any\n```\n\nExample:\n```text\nimport { valueOfPi } from \"./constants.js\"; export const twoPi = valueOfPi * 2;\n```\n\nExample:\n```text\nimport { valueOfPi } from \"./constants.js\";export const twoPi = valueOfPi * 2;\n```\n\nExample:\n```text\n\"use strict\";Object.defineProperty(exports, \"__esModule\", { value: true });exports.twoPi = void 0;const constants_js_1 = require(\"./constants.js\");exports.twoPi = constants_js_1.valueOfPi * 2;\n```\n\nExample:\n```text\n(function (factory) {    if (typeof module === \"object\" && typeof module.exports === \"object\") {        var v = factory(require, exports);        if (v !== undefined) module.exports = v;    }    else if (typeof define === \"function\" && define.amd) {        define([\"require\", \"exports\", \"./constants.js\"], factory);    }})(function (require, exports) {    \"use strict\";    Object.defineProperty(exports, \"__esModule\", { value: true });    exports.twoPi = void 0;    const constants_js_1 = require(\"./constants.js\");    exports.twoPi = constants_js_1.valueOfPi * 2;});\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.354Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":104,"estimatedTokens":950}}25{"id":"doc-typescript_documentation_namespaces_and_modules-149f4996","source":"documentation","title":"TypeScript: Documentation - Namespaces and Modules","url":"https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html","text":"Example:\n```text\n// In a .d.ts file or .ts file that is not a module:declare module \"SomeModule\" {  export function fn(): string;}\n```\n\nExample:\n```text\n/// <reference path=\"myModules.d.ts\" />import * as m from \"SomeModule\";\n```\n\nExample:\n```text\nexport namespace Shapes {  export class Triangle {    /* ... */  }  export class Square {    /* ... */  }}\n```\n\nExample:\n```text\nimport * as shapes from \"./shapes\";let t = new shapes.Shapes.Triangle(); // shapes.Shapes?\n```\n\nExample:\n```text\nexport class Triangle {  /* ... */}export class Square {  /* ... */}\n```\n\nExample:\n```text\nimport * as shapes from \"./shapes\";let t = new shapes.Triangle();\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.355Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":31,"estimatedTokens":166}}26{"id":"doc-typescript_documentation_mapped_types-bad15deb","source":"documentation","title":"TypeScript: Documentation - Mapped Types","url":"https://www.typescriptlang.org/docs/handbook/2/mapped-types.html","text":"Example:\n```text\ntype OnlyBoolsAndHorses = {  [key: string]: boolean | Horse;}; const conforms: OnlyBoolsAndHorses = {  del: true,  rodney: false,};\n```\n\nExample:\n```text\ntype OptionsFlags<Type> = {  [Property in keyof Type]: boolean;};\n```\n\nExample:\n```text\ntype Features = {  darkMode: () => void;  newUserProfile: () => void;}; type FeatureOptions = OptionsFlags<Features>;           type FeatureOptions = {\n    darkMode: boolean;\n    newUserProfile: boolean;\n}\n```\n\nExample:\n```text\n// Removes 'readonly' attributes from a type's propertiestype CreateMutable<Type> = {  -readonly [Property in keyof Type]: Type[Property];}; type LockedAccount = {  readonly id: string;  readonly name: string;}; type UnlockedAccount = CreateMutable<LockedAccount>;           type UnlockedAccount = {\n    id: string;\n    name: string;\n}\n```\n\nExample:\n```text\n// Removes 'optional' attributes from a type's propertiestype Concrete<Type> = {  [Property in keyof Type]-?: Type[Property];}; type MaybeUser = {  id: string;  name?: string;  age?: number;}; type User = Concrete<MaybeUser>;      type User = {\n    id: string;\n    name: string;\n    age: number;\n}\n```\n\nExample:\n```text\ntype MappedTypeWithNewProperties<Type> = {    [Properties in keyof Type as NewKeyType]: Type[Properties]}\n```\n\nExample:\n```text\ntype Getters<Type> = {    [Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]}; interface Person {    name: string;    age: number;    location: string;} type LazyPerson = Getters<Person>;         type LazyPerson = {\n    getName: () => string;\n    getAge: () => number;\n    getLocation: () => string;\n}\n```\n\nExample:\n```text\n// Remove the 'kind' propertytype RemoveKindField<Type> = {    [Property in keyof Type as Exclude<Property, \"kind\">]: Type[Property]}; interface Circle {    kind: \"circle\";    radius: number;} type KindlessCircle = RemoveKindField<Circle>;           type KindlessCircle = {\n    radius: number;\n}\n```\n\nExample:\n```text\ntype EventConfig<Events extends { kind: string }> = {    [E in Events as E[\"kind\"]]: (event: E) => void;} type SquareEvent = { kind: \"square\", x: number, y: number };type CircleEvent = { kind: \"circle\", radius: number }; type Config = EventConfig<SquareEvent | CircleEvent>       type Config = {\n    square: (event: SquareEvent) => void;\n    circle: (event: CircleEvent) => void;\n}\n```\n\nExample:\n```text\ntype ExtractPII<Type> = {  [Property in keyof Type]: Type[Property] extends { pii: true } ? true : false;}; type DBFields = {  id: { format: \"incrementing\" };  name: { type: string; pii: true };}; type ObjectsNeedingGDPRDeletion = ExtractPII<DBFields>;                 type ObjectsNeedingGDPRDeletion = {\n    id: false;\n    name: true;\n}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.355Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":73,"estimatedTokens":683}}27{"id":"doc-typescript_handbook_enums-8d45d887","source":"documentation","title":"TypeScript: Handbook - Enums","url":"https://www.typescriptlang.org/docs/handbook/enums.html","text":"Example:\n```text\nenum Direction {  Up = 1,  Down,  Left,  Right,}\n```\n\nExample:\n```text\nenum Direction {  Up,  Down,  Left,  Right,}\n```\n\nExample:\n```text\nenum UserResponse {  No = 0,  Yes = 1,} function respond(recipient: string, message: UserResponse): void {  // ...} respond(\"Princess Caroline\", UserResponse.Yes);\n```\n\nExample:\n```text\nenum E {  A = getSomeValue(),  B,Enum member must have initializer.1061Enum member must have initializer.}\n```\n\nExample:\n```text\nenum Direction {  Up = \"UP\",  Down = \"DOWN\",  Left = \"LEFT\",  Right = \"RIGHT\",}\n```\n\nExample:\n```text\nenum BooleanLikeHeterogeneousEnum {  No = 0,  Yes = \"YES\",}\n```\n\nExample:\n```text\n// E.X is constant:enum E {  X,}\n```\n\nExample:\n```text\n// All enum members in 'E1' and 'E2' are constant. enum E1 {  X,  Y,  Z,} enum E2 {  A = 1,  B,  C,}\n```\n\nExample:\n```text\nenum FileAccess {  // constant members  None,  Read = 1 << 1,  Write = 1 << 2,  ReadWrite = Read | Write,  // computed member  G = \"123\".length,}\n```\n\nExample:\n```text\nenum ShapeKind {  Circle,  Square,} interface Circle {  kind: ShapeKind.Circle;  radius: number;} interface Square {  kind: ShapeKind.Square;  sideLength: number;} let c: Circle = {  kind: ShapeKind.Square,Type 'ShapeKind.Square' is not assignable to type 'ShapeKind.Circle'.2322Type 'ShapeKind.Square' is not assignable to type 'ShapeKind.Circle'.  radius: 100,};\n```\n\nExample:\n```text\nenum E {  Foo,  Bar,} function f(x: E) {  if (x !== E.Foo || x !== E.Bar) {This comparison appears to be unintentional because the types 'E.Foo' and 'E.Bar' have no overlap.2367This comparison appears to be unintentional because the types 'E.Foo' and 'E.Bar' have no overlap.    //  }}\n```\n\nExample:\n```text\nenum E {  X,  Y,  Z,}\n```\n\nExample:\n```text\nenum E {  X,  Y,  Z,} function f(obj: { X: number }) {  return obj.X;} // Works, since 'E' has a property named 'X' which is a number.f(E);\n```\n\nExample:\n```text\nenum LogLevel {  ERROR,  WARN,  INFO,  DEBUG,} /** * This is equivalent to: * type LogLevelStrings = 'ERROR' | 'WARN' | 'INFO' | 'DEBUG'; */type LogLevelStrings = keyof typeof LogLevel; function printImportant(key: LogLevelStrings, message: string) {  const num = LogLevel[key];  if (num <= LogLevel.WARN) {    console.log(\"Log level key is:\", key);    console.log(\"Log level value is:\", num);    console.log(\"Log level message is:\", message);  }}printImportant(\"ERROR\", \"This is a message\");\n```\n\nExample:\n```text\nenum Enum {  A,} let a = Enum.A;let nameOfA = Enum[a]; // \"A\"\n```\n\nExample:\n```text\n\"use strict\";var Enum;(function (Enum) {    Enum[Enum[\"A\"] = 0] = \"A\";})(Enum || (Enum = {}));let a = Enum.A;let nameOfA = Enum[a]; // \"A\"\n```\n\nExample:\n```text\nconst enum Enum {  A = 1,  B = A * 2,}\n```\n\nExample:\n```text\nconst enum Direction {  Up,  Down,  Left,  Right,} let directions = [  Direction.Up,  Direction.Down,  Direction.Left,  Direction.Right,];\n```\n\nExample:\n```text\n\"use strict\";let directions = [    0 /* Direction.Up */,    1 /* Direction.Down */,    2 /* Direction.Left */,    3 /* Direction.Right */,];\n```\n\nExample:\n```text\ndeclare enum Enum {  A = 1,  B,  C = 2,}\n```\n\nExample:\n```text\nconst enum EDirection {  Up,  Down,  Left,  Right,} const ODirection = {  Up: 0,  Down: 1,  Left: 2,  Right: 3,} as const; EDirection.Up;           (enum member) EDirection.Up = 0 ODirection.Up;           (property) Up: 0 // Using the enum as a parameterfunction walk(dir: EDirection) {} // It requires an extra line to pull out the valuestype Direction = typeof ODirection[keyof typeof ODirection];function run(dir: Direction) {} walk(EDirection.Left);run(ODirection.Right);\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.356Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":106,"estimatedTokens":901}}28{"id":"doc-typescript_documentation_jsx-a56cb05e","source":"documentation","title":"TypeScript: Documentation - JSX","url":"https://www.typescriptlang.org/docs/handbook/jsx.html","text":"Example:\n```text\nconst foo = <Foo>bar;\n```\n\nExample:\n```text\nconst foo = bar as Foo;\n```\n\nExample:\n```text\nexport function createElement(): any;export namespace JSX {  // …}\n```\n\nExample:\n```text\nimport * as React from 'react';\n```\n\nExample:\n```text\nexport function h(props: any): any;export namespace h.JSX {  // …}\n```\n\nExample:\n```text\nimport { h } from 'preact';\n```\n\nExample:\n```text\n{  \"exports\": {    \"./jsx-runtime\": \"./jsx-runtime.js\",    \"./jsx-dev-runtime\": \"./jsx-dev-runtime.js\",  }}\n```\n\nExample:\n```text\nexport namespace JSX {  // …}\n```\n\nExample:\n```text\ndeclare namespace JSX {  interface IntrinsicElements {    foo: any;  }}<foo />; // ok<bar />; // error\n```\n\nExample:\n```text\ndeclare namespace JSX {  interface IntrinsicElements {    [elemName: string]: any;  }}\n```\n\nExample:\n```text\nimport MyComponent from \"./myComponent\";<MyComponent />; // ok<SomeOtherComponent />; // error\n```\n\nExample:\n```text\ninterface FooProp {  name: string;  X: number;  Y: number;}declare function AnotherComponent(prop: { name: string });function ComponentFoo(prop: FooProp) {  return <AnotherComponent name={prop.name} />;}const Button = (prop: { value: string }, context: { color: string }) => (  <button />);\n```\n\nExample:\n```text\ninterface ClickableProps {  children: JSX.Element[] | JSX.Element;} interface HomeProps extends ClickableProps {  home: JSX.Element;} interface SideProps extends ClickableProps {  side: JSX.Element | string;} function MainButton(prop: HomeProps): JSX.Element;function MainButton(prop: SideProps): JSX.Element;function MainButton(prop: ClickableProps): JSX.Element {  // ...}\n```\n\nExample:\n```text\nclass MyComponent {  render() {}}// use a construct signatureconst myComponent = new MyComponent();// element class type => MyComponent// element instance type => { render: () => void }function MyFactoryFunction() {  return {    render: () => {},  };}// use a call signatureconst myComponent = MyFactoryFunction();// element class type => MyFactoryFunction// element instance type => { render: () => void }\n```\n\nExample:\n```text\ndeclare namespace JSX {  interface ElementClass {    render: any;  }}class MyComponent {  render() {}}function MyFactoryFunction() {  return { render: () => {} };}<MyComponent />; // ok<MyFactoryFunction />; // okclass NotAValidComponent {}function NotAValidFactoryFunction() {  return {};}<NotAValidComponent />; // error<NotAValidFactoryFunction />; // error\n```\n\nExample:\n```text\ndeclare namespace JSX {  interface IntrinsicElements {    foo: { bar?: boolean };  }}// element attributes type for 'foo' is '{bar?: boolean}'<foo bar />;\n```\n\nExample:\n```text\ndeclare namespace JSX {  interface ElementAttributesProperty {    props; // specify the property name to use  }}class MyComponent {  // specify the property on the element instance type  props: {    foo?: string;  };}// element attributes type for 'MyComponent' is '{foo?: string}'<MyComponent foo=\"bar\" />;\n```\n\nExample:\n```text\ndeclare namespace JSX {  interface IntrinsicElements {    foo: { requiredProp: string; optionalProp?: number };  }}<foo requiredProp=\"bar\" />; // ok<foo requiredProp=\"bar\" optionalProp={0} />; // ok<foo />; // error, requiredProp is missing<foo requiredProp={0} />; // error, requiredProp should be a string<foo requiredProp=\"bar\" unknownProp />; // error, unknownProp does not exist<foo requiredProp=\"bar\" some-unknown-prop />; // ok, because 'some-unknown-prop' is not a valid identifier\n```\n\nExample:\n```text\nconst props = { requiredProp: \"bar\" };<foo {...props} />; // okconst badProps = {};<foo {...badProps} />; // error\n```\n\nExample:\n```text\ndeclare namespace JSX {  interface ElementChildrenAttribute {    children: {}; // specify children name to use  }}\n```\n\nExample:\n```text\n<div>  <h1>Hello</h1></div>;<div>  <h1>Hello</h1>  World</div>;const CustomComp = (props) => <div>{props.children}</div><CustomComp>  <div>Hello World</div>  {\"This is just a JS expression...\" + 1000}</CustomComp>\n```\n\nExample:\n```text\ninterface PropsType {  children: JSX.Element  name: string}class Component extends React.Component<PropsType, {}> {  render() {    return (      <h2>        {this.props.children}      </h2>    )  }}// OK<Component name=\"foo\">  <h1>Hello World</h1></Component>// Error: children is of type JSX.Element not array of JSX.Element<Component name=\"bar\">  <h1>Hello World</h1>  <h2>Hello World</h2></Component>// Error: children is of type JSX.Element not array of JSX.Element or string.<Component name=\"baz\">  <h1>Hello</h1>  World</Component>\n```\n\nExample:\n```text\nnamespace JSX {    export type ElementType =        // All the valid lowercase tags        | keyof IntrinsicElements        // Function components        | (props: any) => Element        // Class components        | new (props: any) => ElementClass;    export interface IntrinsicAttributes extends /*...*/ {}    export type Element = /*...*/;    export type ElementClass = /*...*/;}\n```\n\nExample:\n```text\nconst a = (  <div>    {[\"foo\", \"bar\"].map((i) => (      <span>{i / 2}</span>    ))}  </div>);\n```\n\nExample:\n```text\nconst a = (  <div>    {[\"foo\", \"bar\"].map(function (i) {      return <span>{i / 2}</span>;    })}  </div>);\n```\n\nExample:\n```text\n/// <reference path=\"react.d.ts\" />interface Props {  foo: string;}class MyComponent extends React.Component<Props, {}> {  render() {    return <span>{this.props.foo}</span>;  }}<MyComponent foo=\"bar\" />; // ok<MyComponent foo={0} />; // error\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.357Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":131,"estimatedTokens":1362}}29{"id":"doc-typescript_documentation_decorators-17c4ca8e","source":"documentation","title":"TypeScript: Documentation - Decorators","url":"https://www.typescriptlang.org/docs/handbook/decorators.html","text":"Example:\n```text\ntsc --target ES5 --experimentalDecorators\n```\n\nExample:\n```typescript\n{  \"compilerOptions\": {    \"target\": \"ES5\",    \"experimentalDecorators\": true  }}\n```\n\nExample:\n```text\nfunction sealed(target) {  // do something with 'target' ...}\n```\n\nExample:\n```text\nfunction color(value: string) {  // this is the decorator factory, it sets up  // the returned decorator function  return function (target) {    // this is the decorator    // do something with 'target' and 'value'...  };}\n```\n\nExample:\n```text\n@f @g x\n```\n\nExample:\n```text\n@f@gx\n```\n\nExample:\n```text\nfunction first() {  console.log(\"first(): factory evaluated\");  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {    console.log(\"first(): called\");  };} function second() {  console.log(\"second(): factory evaluated\");  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {    console.log(\"second(): called\");  };} class ExampleClass {  @first()  @second()  method() {}}\n```\n\nExample:\n```text\nfirst(): factory evaluatedsecond(): factory evaluatedsecond(): calledfirst(): called\n```\n\nExample:\n```text\n@sealedclass BugReport {  type = \"report\";  title: string;   constructor(t: string) {    this.title = t;  }}\n```\n\nExample:\n```text\nfunction sealed(constructor: Function) {  Object.seal(constructor);  Object.seal(constructor.prototype);}\n```\n\nExample:\n```text\nfunction reportableClassDecorator<T extends { new (...args: any[]): {} }>(constructor: T) {  return class extends constructor {    reportingURL = \"http://www...\";  };} @reportableClassDecoratorclass BugReport {  type = \"report\";  title: string;   constructor(t: string) {    this.title = t;  }} const bug = new BugReport(\"Needs dark mode\");console.log(bug.title); // Prints \"Needs dark mode\"console.log(bug.type); // Prints \"report\" // Note that the decorator _does not_ change the TypeScript type// and so the new property `reportingURL` is not known// to the type system:bug.reportingURL;Property 'reportingURL' does not exist on type 'BugReport'.2339Property 'reportingURL' does not exist on type 'BugReport'.\n```\n\nExample:\n```text\nclass Greeter {  greeting: string;  constructor(message: string) {    this.greeting = message;  }   @enumerable(false)  greet() {    return \"Hello, \" + this.greeting;  }}\n```\n\nExample:\n```text\nfunction enumerable(value: boolean) {  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {    descriptor.enumerable = value;  };}\n```\n\nExample:\n```text\nclass Point {  private _x: number;  private _y: number;  constructor(x: number, y: number) {    this._x = x;    this._y = y;  }   @configurable(false)  get x() {    return this._x;  }   @configurable(false)  get y() {    return this._y;  }}\n```\n\nExample:\n```text\nfunction configurable(value: boolean) {  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {    descriptor.configurable = value;  };}\n```\n\nExample:\n```text\nclass Greeter {  @format(\"Hello, %s\")  greeting: string;  constructor(message: string) {    this.greeting = message;  }  greet() {    let formatString = getFormat(this, \"greeting\");    return formatString.replace(\"%s\", this.greeting);  }}\n```\n\nExample:\n```text\nimport \"reflect-metadata\";const formatMetadataKey = Symbol(\"format\");function format(formatString: string) {  return Reflect.metadata(formatMetadataKey, formatString);}function getFormat(target: any, propertyKey: string) {  return Reflect.getMetadata(formatMetadataKey, target, propertyKey);}\n```\n\nExample:\n```text\nclass BugReport {  type = \"report\";  title: string;   constructor(t: string) {    this.title = t;  }   @validate  print(@required verbose: boolean) {    if (verbose) {      return `type: ${this.type}\\ntitle: ${this.title}`;    } else {     return this.title;     }  }}\n```\n\nExample:\n```text\nimport \"reflect-metadata\";const requiredMetadataKey = Symbol(\"required\"); function required(target: Object, propertyKey: string | symbol, parameterIndex: number) {  let existingRequiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey) || [];  existingRequiredParameters.push(parameterIndex);  Reflect.defineMetadata( requiredMetadataKey, existingRequiredParameters, target, propertyKey);} function validate(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) {  let method = descriptor.value!;   descriptor.value = function () {    let requiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyName);    if (requiredParameters) {      for (let parameterIndex of requiredParameters) {        if (parameterIndex >= arguments.length || arguments[parameterIndex] === undefined) {          throw new Error(\"Missing required argument.\");        }      }    }    return method.apply(this, arguments);  };}\n```\n\nExample:\n```text\nnpm i reflect-metadata --save\n```\n\nExample:\n```text\ntsc --target ES5 --experimentalDecorators --emitDecoratorMetadata\n```\n\nExample:\n```typescript\n{  \"compilerOptions\": {    \"target\": \"ES5\",    \"experimentalDecorators\": true,    \"emitDecoratorMetadata\": true  }}\n```\n\nExample:\n```text\nimport \"reflect-metadata\"; class Point {  constructor(public x: number, public y: number) {}} class Line {  private _start: Point;  private _end: Point;   @validate  set start(value: Point) {    this._start = value;  }   get start() {    return this._start;  }   @validate  set end(value: Point) {    this._end = value;  }   get end() {    return this._end;  }} function validate<T>(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<T>) {  let set = descriptor.set!;    descriptor.set = function (value: T) {    let type = Reflect.getMetadata(\"design:type\", target, propertyKey);     if (!(value instanceof type)) {      throw new TypeError(`Invalid type, got ${typeof value} not ${type.name}.`);    }     set.call(this, value);  };} const line = new Line()line.start = new Point(0, 0) // @ts-ignore// line.end = {} // Fails at runtime with:// > Invalid type, got object not Point\n```\n\nExample:\n```text\nclass Line {  private _start: Point;  private _end: Point;  @validate  @Reflect.metadata(\"design:type\", Point)  set start(value: Point) {    this._start = value;  }  get start() {    return this._start;  }  @validate  @Reflect.metadata(\"design:type\", Point)  set end(value: Point) {    this._end = value;  }  get end() {    return this._end;  }}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.358Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":121,"estimatedTokens":1607}}30{"id":"doc-typescript_documentation_using_babel_with_typesc-5ccb2331","source":"documentation","title":"TypeScript: Documentation - Using Babel with TypeScript","url":"https://www.typescriptlang.org/docs/handbook/babel-with-typescript.html","text":"Example:\n```typescript\n\"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}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.358Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":6,"estimatedTokens":70}}31{"id":"doc-typescript_documentation_utility_types-3f97ed4a","source":"documentation","title":"TypeScript: Documentation - Utility Types","url":"https://www.typescriptlang.org/docs/handbook/utility-types.html","text":"Example:\n```text\ntype A = Awaited<Promise<string>>;    type A = string type B = Awaited<Promise<Promise<number>>>;    type B = number type C = Awaited<boolean | Promise<number>>;    type C = number | boolean\n```\n\nExample:\n```text\ninterface Todo {  title: string;  description: string;} function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {  return { ...todo, ...fieldsToUpdate };} const todo1 = {  title: \"organize desk\",  description: \"clear clutter\",}; const todo2 = updateTodo(todo1, {  description: \"throw out trash\",});\n```\n\nExample:\n```text\ninterface Props {  a?: number;  b?: string;} const obj: Props = { a: 5 }; const obj2: Required<Props> = { a: 5 };Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.2741Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.\n```\n\nExample:\n```text\ninterface Todo {  title: string;} const todo: Readonly<Todo> = {  title: \"Delete inactive users\",}; todo.title = \"Hello\";Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.\n```\n\nExample:\n```text\nfunction freeze<Type>(obj: Type): Readonly<Type>;\n```\n\nExample:\n```text\ntype CatName = \"miffy\" | \"boris\" | \"mordred\"; interface CatInfo {  age: number;  breed: string;} const cats: Record<CatName, CatInfo> = {  miffy: { age: 10, breed: \"Persian\" },  boris: { age: 5, breed: \"Maine Coon\" },  mordred: { age: 16, breed: \"British Shorthair\" },}; cats.boris; const cats: Record<CatName, CatInfo>\n```\n\nExample:\n```text\ninterface Todo {  title: string;  description: string;  completed: boolean;} type TodoPreview = Pick<Todo, \"title\" | \"completed\">; const todo: TodoPreview = {  title: \"Clean room\",  completed: false,}; todo; const todo: TodoPreview\n```\n\nExample:\n```text\ninterface Todo {  title: string;  description: string;  completed: boolean;  createdAt: number;} type TodoPreview = Omit<Todo, \"description\">; const todo: TodoPreview = {  title: \"Clean room\",  completed: false,  createdAt: 1615544252770,}; todo; const todo: TodoPreview type TodoInfo = Omit<Todo, \"completed\" | \"createdAt\">; const todoInfo: TodoInfo = {  title: \"Pick up kids\",  description: \"Kindergarten closes at 5pm\",}; todoInfo;   const todoInfo: TodoInfo\n```\n\nExample:\n```text\ntype T0 = Exclude<\"a\" | \"b\" | \"c\", \"a\">;     type T0 = \"b\" | \"c\"type T1 = Exclude<\"a\" | \"b\" | \"c\", \"a\" | \"b\">;     type T1 = \"c\"type T2 = Exclude<string | number | (() => void), Function>;     type T2 = string | number type Shape =  | { kind: \"circle\"; radius: number }  | { kind: \"square\"; x: number }  | { kind: \"triangle\"; x: number; y: number }; type T3 = Exclude<Shape, { kind: \"circle\" }>     type T3 = {\n    kind: \"square\";\n    x: number;\n} | {\n    kind: \"triangle\";\n    x: number;\n    y: number;\n}\n```\n\nExample:\n```text\ntype T0 = Extract<\"a\" | \"b\" | \"c\", \"a\" | \"f\">;     type T0 = \"a\"type T1 = Extract<string | number | (() => void), Function>;     type T1 = () => void type Shape =  | { kind: \"circle\"; radius: number }  | { kind: \"square\"; x: number }  | { kind: \"triangle\"; x: number; y: number }; type T2 = Extract<Shape, { kind: \"circle\" }>     type T2 = {\n    kind: \"circle\";\n    radius: number;\n}\n```\n\nExample:\n```text\ntype T0 = NonNullable<string | number | undefined>;     type T0 = string | numbertype T1 = NonNullable<string[] | null | undefined>;     type T1 = string[]\n```\n\nExample:\n```text\ndeclare function f1(arg: { a: number; b: string }): void; type T0 = Parameters<() => string>;     type T0 = []type T1 = Parameters<(s: string) => void>;     type T1 = [s: string]type T2 = Parameters<<T>(arg: T) => T>;     type T2 = [arg: unknown]type T3 = Parameters<typeof f1>;     type T3 = [arg: {\n    a: number;\n    b: string;\n}]type T4 = Parameters<any>;     type T4 = unknown[]type T5 = Parameters<never>;     type T5 = nevertype T6 = Parameters<string>;Type 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.     type T6 = nevertype T7 = Parameters<Function>;Type 'Function' does not satisfy the constraint '(...args: any) => any'.\n  Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'.\n  Type 'Function' provides no match for the signature '(...args: any): any'.     type T7 = never\n```\n\nExample:\n```text\ntype T0 = ConstructorParameters<ErrorConstructor>;     type T0 = [message?: string]type T1 = ConstructorParameters<FunctionConstructor>;     type T1 = string[]type T2 = ConstructorParameters<RegExpConstructor>;     type T2 = [pattern: string | RegExp, flags?: string]class C {  constructor(a: number, b: string) {}}type T3 = ConstructorParameters<typeof C>;     type T3 = [a: number, b: string]type T4 = ConstructorParameters<any>;     type T4 = unknown[] type T5 = ConstructorParameters<Function>;Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.\n  Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.\n  Type 'Function' provides no match for the signature 'new (...args: any): any'.     type T5 = never\n```\n\nExample:\n```text\ndeclare function f1(): { a: number; b: string }; type T0 = ReturnType<() => string>;     type T0 = stringtype T1 = ReturnType<(s: string) => void>;     type T1 = voidtype T2 = ReturnType<<T>() => T>;     type T2 = unknowntype T3 = ReturnType<<T extends U, U extends number[]>() => T>;     type T3 = number[]type T4 = ReturnType<typeof f1>;     type T4 = {\n    a: number;\n    b: string;\n}type T5 = ReturnType<any>;     type T5 = anytype T6 = ReturnType<never>;     type T6 = nevertype T7 = ReturnType<string>;Type 'string' does not satisfy the constraint '(...args: any) => any'.2344Type 'string' does not satisfy the constraint '(...args: any) => any'.     type T7 = anytype T8 = ReturnType<Function>;Type 'Function' does not satisfy the constraint '(...args: any) => any'.\n  Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the constraint '(...args: any) => any'.\n  Type 'Function' provides no match for the signature '(...args: any): any'.     type T8 = any\n```\n\nExample:\n```text\nclass C {  x = 0;  y = 0;} type T0 = InstanceType<typeof C>;     type T0 = Ctype T1 = InstanceType<any>;     type T1 = anytype T2 = InstanceType<never>;     type T2 = nevertype T3 = InstanceType<string>;Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.     type T3 = anytype T4 = InstanceType<Function>;Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.\n  Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.\n  Type 'Function' provides no match for the signature 'new (...args: any): any'.     type T4 = any\n```\n\nExample:\n```text\nfunction createStreetLight<C extends string>(  colors: C[],  defaultColor?: NoInfer<C>,) {  // ...}createStreetLight([\"red\", \"yellow\", \"green\"], \"red\");  // OKcreateStreetLight([\"red\", \"yellow\", \"green\"], \"blue\");  // Error\n```\n\nExample:\n```text\nfunction toHex(this: Number) {  return this.toString(16);} function numberToString(n: ThisParameterType<typeof toHex>) {  return toHex.apply(n);}\n```\n\nExample:\n```text\nfunction toHex(this: Number) {  return this.toString(16);} const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5); console.log(fiveToHex());\n```\n\nExample:\n```text\ntype ObjectDescriptor<D, M> = {  data?: D;  methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M}; function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {  let data: object = desc.data || {};  let methods: object = desc.methods || {};  return { ...data, ...methods } as D & M;} let obj = makeObject({  data: { x: 0, y: 0 },  methods: {    moveBy(dx: number, dy: number) {      this.x += dx; // Strongly typed this      this.y += dy; // Strongly typed this    },  },}); obj.x = 10;obj.y = 20;obj.moveBy(5, 5);\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.359Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":120,"estimatedTokens":2067}}32{"id":"doc-typescript_documentation_asp_net_core-2d6b610c","source":"documentation","title":"TypeScript: Documentation - ASP.NET Core","url":"https://www.typescriptlang.org/docs/handbook/asp-net-core.html","text":"Example:\n```text\npublic void Configure(IApplicationBuilder app, IHostEnvironment env)\n{\n    if (env.IsDevelopment())\n    {\n        app.UseDeveloperExceptionPage();\n    }\n\n    app.UseDefaultFiles();\n    app.UseStaticFiles();\n}\n```\n\nExample:\n```text\nfunction sayHello() {  const compiler = (document.getElementById(\"compiler\") as HTMLInputElement)    .value;  const framework = (document.getElementById(\"framework\") as HTMLInputElement)    .value;  return `Hello from ${compiler} and ${framework}!`;}\n```\n\nExample:\n```typescript\n{  \"compilerOptions\": {    \"noEmitOnError\": true,    \"noImplicitAny\": true,    \"sourceMap\": true,    \"target\": \"es6\"  },  \"files\": [\"./app.ts\"],  \"compileOnSave\": true}\n```\n\nExample:\n```typescript\n\"devDependencies\": {    \"gulp\": \"4.0.2\",    \"del\": \"5.1.0\"}\n```\n\nExample:\n```text\n/// <binding AfterBuild='default' Clean='clean' />/*This file is the main entry point for defining Gulp tasks and using Gulp plugins.Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007*/var gulp = require(\"gulp\");var del = require(\"del\");var paths = {  scripts: [\"scripts/**/*.js\", \"scripts/**/*.ts\", \"scripts/**/*.map\"],};gulp.task(\"clean\", function () {  return del([\"wwwroot/scripts/**/*\"]);});gulp.task(\"default\", function (done) {    gulp.src(paths.scripts).pipe(gulp.dest(\"wwwroot/scripts\"));    done();});\n```\n\nExample:\n```text\n<!DOCTYPE html><html><head>    <meta charset=\"utf-8\" />    <script src=\"scripts/app.js\"></script>    <title></title></head><body>    <div id=\"message\"></div>    <div>        Compiler: <input id=\"compiler\" value=\"TypeScript\" onkeyup=\"document.getElementById('message').innerText = sayHello()\" /><br />        Framework: <input id=\"framework\" value=\"ASP.NET\" onkeyup=\"document.getElementById('message').innerText = sayHello()\" />    </div></body></html>\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.359Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":40,"estimatedTokens":458}}33{"id":"doc-typescript_documentation_modules_choosing_compil-b70b2622","source":"documentation","title":"TypeScript: Documentation - Modules - Choosing Compiler Options","url":"https://www.typescriptlang.org/docs/handbook/modules/guides/choosing-compiler-options.html","text":"Example:\n```text\n{  \"compilerOptions\": {    // This is not a complete template; it only    // shows relevant module-related settings.    // Be sure to set other important options    // like `target`, `lib`, and `strict`.    // Required    \"module\": \"esnext\",    \"moduleResolution\": \"bundler\",    \"esModuleInterop\": true,    // Consult your bundler’s documentation    \"customConditions\": [\"module\"],    // Recommended    \"noEmit\": true, // or `emitDeclarationOnly`    \"allowImportingTsExtensions\": true,    \"allowArbitraryExtensions\": true,    \"verbatimModuleSyntax\": true, // or `isolatedModules`  }}\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    // This is not a complete template; it only    // shows relevant module-related settings.    // Be sure to set other important options    // like `target`, `lib`, and `strict`.    // Required    \"module\": \"nodenext\",    // Implied by `\"module\": \"nodenext\"`:    // \"moduleResolution\": \"nodenext\",    // \"esModuleInterop\": true,    // \"target\": \"esnext\",    // Recommended    \"verbatimModuleSyntax\": true,  }}\n```\n\nExample:\n```text\n// tsconfig.json{  \"compilerOptions\": {    // This is not a complete template; it only    // shows relevant module-related settings.    // Be sure to set other important options    // like `target`, `lib`, and `strict`.    // Combined with `\"type\": \"module\"` in a local package.json,    // this enforces including file extensions on relative path imports.    \"module\": \"nodenext\",    \"paths\": {      // Point TS to local types for remote URLs:      \"https://esm.sh/lodash@4.17.21\": [\"./node_modules/@types/lodash/index.d.ts\"],      // Optional: point bare specifier imports to an empty file      // to prohibit importing from node_modules specifiers not listed here:      \"*\": [\"./empty-file.ts\"]    }  }}\n```\n\nExample:\n```text\nimport {} from \"lodash\";//             ^^^^^^^^// File '/project/empty-file.ts' is not a module. ts(2306)\n```\n\nExample:\n```text\n<script type=\"importmap\">{  \"imports\": {    \"lodash\": \"https://esm.sh/lodash@4.17.21\"  }}</script>\n```\n\nExample:\n```text\nimport {} from \"lodash\";// Browser: https://esm.sh/lodash@4.17.21// TypeScript: ./node_modules/@types/lodash/index.d.ts\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"module\": \"node18\",    \"target\": \"es2020\", // set to the *lowest* target you support    \"strict\": true,    \"verbatimModuleSyntax\": true,    \"declaration\": true,    \"sourceMap\": true,    \"declarationMap\": true,    \"rootDir\": \"src\",    \"outDir\": \"dist\"  }}\n```\n\nExample:\n```text\nexport * from \"./utils\";\n```\n\nExample:\n```text\nError [ERR_MODULE_NOT_FOUND]: Cannot find module '.../node_modules/dependency/utils' imported from .../node_modules/dependency/index.jsDid you mean to import ./utils.js?\n```\n\nExample:\n```text\nexport * from \"./utils.js\";\n```\n\nExample:\n```text\nexport interface Super {  foo: string;}export interface Sub extends Super {  foo: string | undefined;}\n```\n\nExample:\n```text\nimport { Component } from \"./extensionless-relative-import\";\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.360Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":61,"estimatedTokens":749}}34{"id":"doc-typescript_documentation_declaration_reference-5e95b234","source":"documentation","title":"TypeScript: Documentation - Declaration Reference","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html","text":"Example:\n```text\nlet result = myLib.makeGreeting(\"hello, world\");console.log(\"The computed greeting is:\" + result);let count = myLib.numberOfGreetings;\n```\n\nExample:\n```text\ndeclare namespace myLib {  function makeGreeting(s: string): string;  let numberOfGreetings: number;}\n```\n\nExample:\n```text\nlet x: Widget = getWidget(43);let arr: Widget[] = getWidget(\"all of them\");\n```\n\nExample:\n```text\ndeclare function getWidget(n: number): Widget;declare function getWidget(s: string): Widget[];\n```\n\nExample:\n```text\ngreet({  greeting: \"hello world\",  duration: 4000});\n```\n\nExample:\n```text\ninterface GreetingSettings {  greeting: string;  duration?: number;  color?: string;}declare function greet(setting: GreetingSettings): void;\n```\n\nExample:\n```text\nfunction getGreeting() {  return \"howdy\";}class MyGreeter extends Greeter {}greet(\"hello\");greet(getGreeting);greet(new MyGreeter());\n```\n\nExample:\n```text\ntype GreetingLike = string | (() => string) | MyGreeter;declare function greet(g: GreetingLike): void;\n```\n\nExample:\n```text\nconst g = new Greeter(\"Hello\");g.log({ verbose: true });g.alert({ modal: false, title: \"Current Greeting\" });\n```\n\nExample:\n```text\ndeclare namespace GreetingLib {  interface LogOptions {    verbose?: boolean;  }  interface AlertOptions {    modal: boolean;    title?: string;    color?: string;  }}\n```\n\nExample:\n```text\ndeclare namespace GreetingLib.Options {  // Refer to via GreetingLib.Options.Log  interface Log {    verbose?: boolean;  }  interface Alert {    modal: boolean;    title?: string;    color?: string;  }}\n```\n\nExample:\n```text\nconst myGreeter = new Greeter(\"hello, world\");myGreeter.greeting = \"howdy\";myGreeter.showGreeting();class SpecialGreeter extends Greeter {  constructor() {    super(\"Very special greetings\");  }}\n```\n\nExample:\n```text\ndeclare class Greeter {  constructor(greeting: string);  greeting: string;  showGreeting(): void;}\n```\n\nExample:\n```text\nconsole.log(\"Half the number of widgets is \" + foo / 2);\n```\n\nExample:\n```text\n/** The number of widgets present */declare var foo: number;\n```\n\nExample:\n```text\ngreet(\"hello, world\");\n```\n\nExample:\n```text\ndeclare function greet(greeting: string): void;\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.360Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":86,"estimatedTokens":548}}35{"id":"doc-typescript_documentation_type_compatibility-b1f557c0","source":"documentation","title":"TypeScript: Documentation - Type Compatibility","url":"https://www.typescriptlang.org/docs/handbook/type-compatibility.html","text":"Example:\n```text\ninterface Pet {  name: string;}class Dog {  name: string;}let pet: Pet;// OK, because of structural typingpet = new Dog();\n```\n\nExample:\n```text\ninterface Pet {  name: string;}let pet: Pet;// dog's inferred type is { name: string; owner: string; }let dog = { name: \"Lassie\", owner: \"Rudd Weatherwax\" };pet = dog;\n```\n\nExample:\n```text\ninterface Pet {  name: string;}let dog = { name: \"Lassie\", owner: \"Rudd Weatherwax\" };function greet(pet: Pet) {  console.log(\"Hello, \" + pet.name);}greet(dog); // OK\n```\n\nExample:\n```text\nlet dog: Pet = { name: \"Lassie\", owner: \"Rudd Weatherwax\" }; // Error\n```\n\nExample:\n```text\nlet x = (a: number) => 0;let y = (b: number, s: string) => 0;y = x; // OKx = y; // Error\n```\n\nExample:\n```text\nlet items = [1, 2, 3];// Don't force these extra parametersitems.forEach((item, index, array) => console.log(item));// Should be OK!items.forEach((item) => console.log(item));\n```\n\nExample:\n```text\nlet x = () => ({ name: \"Alice\" });let y = () => ({ name: \"Alice\", location: \"Seattle\" });x = y; // OKy = x; // Error, because x() lacks a location property\n```\n\nExample:\n```text\nenum EventType {  Mouse,  Keyboard,}interface Event {  timestamp: number;}interface MyMouseEvent extends Event {  x: number;  y: number;}interface MyKeyEvent extends Event {  keyCode: number;}function listenEvent(eventType: EventType, handler: (n: Event) => void) {  /* ... */}// Unsound, but useful and commonlistenEvent(EventType.Mouse, (e: MyMouseEvent) => console.log(e.x + \",\" + e.y));// Undesirable alternatives in presence of soundnesslistenEvent(EventType.Mouse, (e: Event) =>  console.log((e as MyMouseEvent).x + \",\" + (e as MyMouseEvent).y));listenEvent(EventType.Mouse, ((e: MyMouseEvent) =>  console.log(e.x + \",\" + e.y)) as (e: Event) => void);// Still disallowed (clear error). Type safety enforced for wholly incompatible typeslistenEvent(EventType.Mouse, (e: number) => console.log(e));\n```\n\nExample:\n```text\nfunction invokeLater(args: any[], callback: (...args: any[]) => void) {  /* ... Invoke callback with 'args' ... */}// Unsound - invokeLater \"might\" provide any number of argumentsinvokeLater([1, 2], (x, y) => console.log(x + \", \" + y));// Confusing (x and y are actually required) and undiscoverableinvokeLater([1, 2], (x?, y?) => console.log(x + \", \" + y));\n```\n\nExample:\n```text\nenum Status {  Ready,  Waiting,}enum Color {  Red,  Blue,  Green,}let status = Status.Ready;status = Color.Green; // Error\n```\n\nExample:\n```text\nclass Animal {  feet: number;  constructor(name: string, numFeet: number) {}}class Size {  feet: number;  constructor(numFeet: number) {}}let a: Animal;let s: Size;a = s; // OKs = a; // OK\n```\n\nExample:\n```text\ninterface Empty<T> {}let x: Empty<number>;let y: Empty<string>;x = y; // OK, because y matches structure of x\n```\n\nExample:\n```text\ninterface NotEmpty<T> {  data: T;}let x: NotEmpty<number>;let y: NotEmpty<string>;x = y; // Error, because x and y are not compatible\n```\n\nExample:\n```text\nlet identity = function <T>(x: T): T {  // ...};let reverse = function <U>(y: U): U {  // ...};identity = reverse; // OK, because (x: any) => any matches (y: any) => any\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.361Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":71,"estimatedTokens":790}}36{"id":"doc-typescript_documentation_gulp-14626be6","source":"documentation","title":"TypeScript: Documentation - Gulp","url":"https://www.typescriptlang.org/docs/handbook/gulp.html","text":"Example:\n```text\nmkdir projcd proj\n```\n\nExample:\n```text\nproj/   ├─ src/   └─ dist/\n```\n\nExample:\n```text\nmkdir srcmkdir dist\n```\n\nExample:\n```text\nnpm init\n```\n\nExample:\n```text\nnpm install -g gulp-cli\n```\n\nExample:\n```text\nnpm install --save-dev typescript gulp@4.0.0 gulp-typescript\n```\n\nExample:\n```text\nfunction hello(compiler: string) {  console.log(`Hello from ${compiler}`);}hello(\"TypeScript\");\n```\n\nExample:\n```typescript\n{  \"files\": [\"src/main.ts\"],  \"compilerOptions\": {    \"noImplicitAny\": true,    \"target\": \"es5\"  }}\n```\n\nExample:\n```text\nvar gulp = require(\"gulp\");var ts = require(\"gulp-typescript\");var tsProject = ts.createProject(\"tsconfig.json\");gulp.task(\"default\", function () {  return tsProject.src().pipe(tsProject()).js.pipe(gulp.dest(\"dist\"));});\n```\n\nExample:\n```text\ngulpnode dist/main.js\n```\n\nExample:\n```text\nexport function sayHello(name: string) {  return `Hello from ${name}`;}\n```\n\nExample:\n```text\nimport { sayHello } from \"./greet\";console.log(sayHello(\"TypeScript\"));\n```\n\nExample:\n```typescript\n{  \"files\": [\"src/main.ts\", \"src/greet.ts\"],  \"compilerOptions\": {    \"noImplicitAny\": true,    \"target\": \"es5\"  }}\n```\n\nExample:\n```text\nnpm install --save-dev browserify tsify vinyl-source-stream\n```\n\nExample:\n```text\n<!DOCTYPE html><html>  <head>    <meta charset=\"UTF-8\" />    <title>Hello World!</title>  </head>  <body>    <p id=\"greeting\">Loading ...</p>    <script src=\"bundle.js\"></script>  </body></html>\n```\n\nExample:\n```text\nimport { sayHello } from \"./greet\";function showHello(divName: string, name: string) {  const elt = document.getElementById(divName);  elt.innerText = sayHello(name);}showHello(\"greeting\", \"TypeScript\");\n```\n\nExample:\n```text\nvar gulp = require(\"gulp\");var browserify = require(\"browserify\");var source = require(\"vinyl-source-stream\");var tsify = require(\"tsify\");var paths = {  pages: [\"src/*.html\"],};gulp.task(\"copy-html\", function () {  return gulp.src(paths.pages).pipe(gulp.dest(\"dist\"));});gulp.task(  \"default\",  gulp.series(gulp.parallel(\"copy-html\"), function () {    return browserify({      basedir: \".\",      debug: true,      entries: [\"src/main.ts\"],      cache: {},      packageCache: {},    })      .plugin(tsify)      .bundle()      .pipe(source(\"bundle.js\"))      .pipe(gulp.dest(\"dist\"));  }));\n```\n\nExample:\n```text\nnpm install --save-dev watchify fancy-log\n```\n\nExample:\n```text\nvar gulp = require(\"gulp\");var browserify = require(\"browserify\");var source = require(\"vinyl-source-stream\");var watchify = require(\"watchify\");var tsify = require(\"tsify\");var fancy_log = require(\"fancy-log\");var paths = {  pages: [\"src/*.html\"],};var watchedBrowserify = watchify(  browserify({    basedir: \".\",    debug: true,    entries: [\"src/main.ts\"],    cache: {},    packageCache: {},  }).plugin(tsify));gulp.task(\"copy-html\", function () {  return gulp.src(paths.pages).pipe(gulp.dest(\"dist\"));});function bundle() {  return watchedBrowserify    .bundle()    .on(\"error\", fancy_log)    .pipe(source(\"bundle.js\"))    .pipe(gulp.dest(\"dist\"));}gulp.task(\"default\", gulp.series(gulp.parallel(\"copy-html\"), bundle));watchedBrowserify.on(\"update\", bundle);watchedBrowserify.on(\"log\", fancy_log);\n```\n\nExample:\n```text\nproj$ gulp[10:34:20] Using gulpfile ~/src/proj/gulpfile.js[10:34:20] Starting 'copy-html'...[10:34:20] Finished 'copy-html' after 26 ms[10:34:20] Starting 'default'...[10:34:21] 2824 bytes written (0.13 seconds)[10:34:21] Finished 'default' after 1.36 s[10:35:22] 2261 bytes written (0.02 seconds)[10:35:24] 2808 bytes written (0.05 seconds)\n```\n\nExample:\n```text\nnpm install --save-dev gulp-terser vinyl-buffer gulp-sourcemaps\n```\n\nExample:\n```text\nvar gulp = require(\"gulp\");var browserify = require(\"browserify\");var source = require(\"vinyl-source-stream\");var terser = require(\"gulp-terser\");var tsify = require(\"tsify\");var sourcemaps = require(\"gulp-sourcemaps\");var buffer = require(\"vinyl-buffer\");var paths = {  pages: [\"src/*.html\"],};gulp.task(\"copy-html\", function () {  return gulp.src(paths.pages).pipe(gulp.dest(\"dist\"));});gulp.task(  \"default\",  gulp.series(gulp.parallel(\"copy-html\"), function () {    return browserify({      basedir: \".\",      debug: true,      entries: [\"src/main.ts\"],      cache: {},      packageCache: {},    })      .plugin(tsify)      .bundle()      .pipe(source(\"bundle.js\"))      .pipe(buffer())      .pipe(sourcemaps.init({ loadMaps: true }))      .pipe(terser())      .pipe(sourcemaps.write(\"./\"))      .pipe(gulp.dest(\"dist\"));  }));\n```\n\nExample:\n```text\ngulpcat dist/bundle.js\n```\n\nExample:\n```text\nnpm install --save-dev babelify@8 babel-core babel-preset-es2015 vinyl-buffer gulp-sourcemaps\n```\n\nExample:\n```text\nvar gulp = require(\"gulp\");var browserify = require(\"browserify\");var source = require(\"vinyl-source-stream\");var tsify = require(\"tsify\");var sourcemaps = require(\"gulp-sourcemaps\");var buffer = require(\"vinyl-buffer\");var paths = {  pages: [\"src/*.html\"],};gulp.task(\"copy-html\", function () {  return gulp.src(paths.pages).pipe(gulp.dest(\"dist\"));});gulp.task(  \"default\",  gulp.series(gulp.parallel(\"copy-html\"), function () {    return browserify({      basedir: \".\",      debug: true,      entries: [\"src/main.ts\"],      cache: {},      packageCache: {},    })      .plugin(tsify)      .transform(\"babelify\", {        presets: [\"es2015\"],        extensions: [\".ts\"],      })      .bundle()      .pipe(source(\"bundle.js\"))      .pipe(buffer())      .pipe(sourcemaps.init({ loadMaps: true }))      .pipe(sourcemaps.write(\"./\"))      .pipe(gulp.dest(\"dist\"));  }));\n```\n\nExample:\n```typescript\n{  \"files\": [\"src/main.ts\"],  \"compilerOptions\": {    \"noImplicitAny\": true,    \"target\": \"es2015\"  }}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.361Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":131,"estimatedTokens":1420}}37{"id":"doc-typescript_documentation_migrating_from_javascri-3877942c","source":"documentation","title":"TypeScript: Documentation - Migrating from JavaScript","url":"https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html","text":"Example:\n```text\nprojectRoot├── src│   ├── file1.js│   └── file2.js├── built└── tsconfig.json\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"outDir\": \"./built\",    \"allowJs\": true,    \"target\": \"es5\"  },  \"include\": [\"./src/**/*\"]}\n```\n\nExample:\n```text\nnpm install ts-loader source-map-loader\n```\n\nExample:\n```text\nmodule.exports = {  entry: \"./src/index.ts\",  output: {    filename: \"./dist/bundle.js\",  },  // Enable sourcemaps for debugging webpack's output.  devtool: \"source-map\",  resolve: {    // Add '.ts' and '.tsx' as resolvable extensions.    extensions: [\"\", \".webpack.js\", \".web.js\", \".ts\", \".tsx\", \".js\"],  },  module: {    rules: [      // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.      { test: /\\.tsx?$/, loader: \"ts-loader\" },      // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.      { test: /\\.js$/, loader: \"source-map-loader\" },    ],  },  // Other options...};\n```\n\nExample:\n```text\n// For Node/CommonJSdeclare function require(path: string): any;\n```\n\nExample:\n```text\n// For RequireJS/AMDdeclare function define(...args: any[]): any;\n```\n\nExample:\n```text\nvar foo = require(\"foo\");foo.doStuff();\n```\n\nExample:\n```text\ndefine([\"foo\"], function (foo) {  foo.doStuff();});\n```\n\nExample:\n```text\nimport foo = require(\"foo\");foo.doStuff();\n```\n\nExample:\n```text\nnpm install -S @types/lodash\n```\n\nExample:\n```text\nmodule.exports.feedPets = function (pets) {  // ...};\n```\n\nExample:\n```text\nexport function feedPets(pets) {  // ...}\n```\n\nExample:\n```text\nvar express = require(\"express\");var app = express();\n```\n\nExample:\n```text\nfunction foo() {  // ...}module.exports = foo;\n```\n\nExample:\n```text\nfunction foo() {  // ...}export = foo;\n```\n\nExample:\n```text\nfunction myCoolFunction() {  if (arguments.length == 2 && !Array.isArray(arguments[1])) {    var f = arguments[0];    var arr = arguments[1];    // ...  }  // ...}myCoolFunction(  function (x) {    console.log(x);  },  [1, 2, 3, 4]);myCoolFunction(  function (x) {    console.log(x);  },  1,  2,  3,  4);\n```\n\nExample:\n```text\nfunction myCoolFunction(f: (x: number) => void, nums: number[]): void;function myCoolFunction(f: (x: number) => void, ...nums: number[]): void;function myCoolFunction() {  if (arguments.length == 2 && !Array.isArray(arguments[1])) {    var f = arguments[0];    var arr = arguments[1];    // ...  }  // ...}\n```\n\nExample:\n```text\nvar options = {};options.color = \"red\";options.volume = 11;\n```\n\nExample:\n```text\nlet options = {  color: \"red\",  volume: 11,};\n```\n\nExample:\n```text\ninterface Options {  color: string;  volume: number;}let options = {} as Options;options.color = \"red\";options.volume = 11;\n```\n\nExample:\n```text\ndeclare var foo: string[] | null;foo.length; // error - 'foo' is possibly 'null'foo!.length; // okay - 'foo!' just has type 'string[]'\n```\n\nExample:\n```text\nclass Point {  constructor(public x, public y) {}  getDistance(p: Point) {    let dx = p.x - this.x;    let dy = p.y - this.y;    return Math.sqrt(dx ** 2 + dy ** 2);  }}// ...// Reopen the interface.interface Point {  distanceFromOrigin(): number;}Point.prototype.distanceFromOrigin = function () {  return this.getDistance({ x: 0, y: 0 });};\n```\n\nExample:\n```text\nPoint.prototype.distanceFromOrigin = function (this: Point) {  return this.getDistance({ x: 0, y: 0 });};\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.362Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":116,"estimatedTokens":839}}38{"id":"doc-typescript_documentation_modules_esm_cjs_interop-ed6daa68","source":"documentation","title":"TypeScript: Documentation - Modules - ESM/CJS Interoperability","url":"https://www.typescriptlang.org/docs/handbook/modules/appendices/esm-cjs-interop.html","text":"Example:\n```text\nexport const A = {};export const B = {};export default \"Hello, world!\";\n```\n\nExample:\n```text\nexports.A = {};exports.B = {};exports.default = \"Hello, world!\";\n```\n\nExample:\n```text\nimport hello, { A, B } from \"./module\";console.log(hello, A, B);// transpiles to:const module_1 = require(\"./module\");console.log(module_1.default, module_1.A, module_1.B);\n```\n\nExample:\n```text\nimport * as mod from \"./module\";console.log(mod.default, mod.A, mod.B);// transpiles to:const mod = require(\"./module\");console.log(mod.default, mod.A, mod.B);\n```\n\nExample:\n```text\n// @Filename: exports-function.jsmodule.exports = function hello() {  console.log(\"Hello, world!\");};\n```\n\nExample:\n```text\nimport * as hello from \"./exports-function\";hello();// transpiles to:const hello = require(\"./exports-function\");hello();\n```\n\nExample:\n```text\n// Invalid according to the spec:import * as hello from \"./exports-function\";hello();// but the transpilation works:const hello = require(\"./exports-function\");hello();\n```\n\nExample:\n```text\nimport * as hello from \"./exports-function\";// TS2497              ^^^^^^^^^^^^^^^^^^^^// External module '\"./exports-function\"' resolves to a non-module entity// and cannot be imported using this construct.\n```\n\nExample:\n```text\nimport hello = require(\"./exports-function\");\n```\n\nExample:\n```text\ndeclare function $(selector: string): any;export = $; // Cannot `import *` this 👍\n```\n\nExample:\n```text\ndeclare namespace $ {}declare function $(selector: string): any;export = $; // Allowed to `import *` this and call it 😱\n```\n\nExample:\n```text\nexports.A = {};exports.B = {};exports.default = \"Hello, world!\";// Extra special flag!exports.__esModule = true;\n```\n\nExample:\n```text\n// import hello from \"./module\";const _mod = require(\"./module\");const hello = _mod.__esModule ? _mod.default : _mod;\n```\n\nExample:\n```text\n// Error:import * as hello from \"./exports-function\";// Old workaround:import hello = require(\"./exports-function\");// New way, with `allowSyntheticDefaultImports`:import hello from \"./exports-function\";\n```\n\nExample:\n```text\n// @Filename: exportEqualsObject.d.tsdeclare const obj: object;export = obj;// @Filename: main.tsimport objDefault from \"./exportEqualsObject\";import * as objNamespace from \"./exportEqualsObject\";// This should be true at runtime, but TypeScript gives an error:objNamespace.default === objDefault;//           ^^^^^^^ Property 'default' does not exist on type 'typeof import(\"./exportEqualsObject\")'.\n```\n\nExample:\n```text\n// @Filename: export.cjsmodule.exports = { hello: \"world\" };// @Filename: import.mjsimport greeting from \"./export.cjs\";greeting.hello; // \"world\"\n```\n\nExample:\n```text\n// @Filename: node_modules/dependency/index.jsexports.__esModule = true;exports.default = function doSomething() { /*...*/ }// @Filename: transpile-vs-run-directly.{js/mjs}import doSomething from \"dependency\";// Works after transpilation, but not a function in Node.js ESM:doSomething();// Doesn't exist after transpilation, but works in Node.js ESM:doSomething.default();\n```\n\nExample:\n```text\n// @Filename: named-exports.cjsexports.hello = \"world\";exports[\"worl\" + \"d\"] = \"hello\";// @Filename: transpile-vs-run-directly.{js/mjs}import { hello, world } from \"./named-exports.cjs\";// `hello` works, but `world` is missing in Node.js 💥import mod from \"./named-exports.cjs\";mod.world;// Accessing properties from the default always works ✅\n```\n\nExample:\n```text\n// @Filename: node_modules/dependency/index.jsexport function doSomething() { /* ... */ }// @Filename: dependent.jsimport { doSomething } from \"dependency\";// ✅ Works if dependent and dependency are both transpiled// ✅ Works if dependent and dependency are both true ESM// ✅ Works if dependent is true ESM and dependency is transpiled// 💥 Crashes if dependent is transpiled and dependency is true ESM\n```\n\nExample:\n```text\n// @Filename: add.jsexport function add(a, b) {  return a + b;}// @Filename: math.jsexport * from \"./add\";//            ^^^^^^^// Works when transpiled to CJS,// but would have to be \"./add.js\"// in Node.js ESM.\n```\n\nExample:\n```text\n// @Filename: node_modules/transpiled-dependency/index.jsexports.__esModule = true;exports.default = function doSomething() { /* ... */ };exports.something = \"something\";// @Filename: node_modules/true-cjs-dependency/index.jsmodule.exports = function doSomethingElse() { /* ... */ };// @Filename: src/sayHello.tsexport default function sayHello() { /* ... */ }export const hello = \"hello\";// @Filename: src/main.tsimport doSomething from \"transpiled-dependency\";import doSomethingElse from \"true-cjs-dependency\";import sayHello from \"./sayHello.js\";\n```\n\nExample:\n```text\nimport pkg from \"pkg\";pkg.default();\n```\n\nExample:\n```text\nimport pkg from \"pkg\";pkg();\n```\n\nExample:\n```text\nconst pkg = require(\"pkg\");pkg.default();\n```\n\nExample:\n```text\n- export default function doSomething() { /* ... */ }+ export = function doSomething() { /* ... */ }\n```\n\nExample:\n```text\n// @Filename: /node_modules/dependency/index.d.tsimport express from \"express\";declare function doSomething(req: express.Request): any;export = doSomething;\n```\n\nExample:\n```text\nimport express = require(\"express\");// ...\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.364Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":136,"estimatedTokens":1300}}39{"id":"doc-typescript_documentation_type_inference-3c84c124","source":"documentation","title":"TypeScript: Documentation - Type Inference","url":"https://www.typescriptlang.org/docs/handbook/type-inference.html","text":"Example:\n```text\nlet x = 3;   let x: number\n```\n\nExample:\n```text\nlet x = [0, 1, null];   let x: (number | null)[]\n```\n\nExample:\n```text\nlet zoo = [new Rhino(), new Elephant(), new Snake()];    let zoo: (Rhino | Elephant | Snake)[]\n```\n\nExample:\n```text\nlet zoo: Animal[] = [new Rhino(), new Elephant(), new Snake()];    let zoo: Animal[]\n```\n\nExample:\n```text\nwindow.onmousedown = function (mouseEvent) {  console.log(mouseEvent.button);  console.log(mouseEvent.kangaroo);Property 'kangaroo' does not exist on type 'MouseEvent'.2339Property 'kangaroo' does not exist on type 'MouseEvent'.};\n```\n\nExample:\n```text\n// Declares there is a global variable called 'window'declare var window: Window & typeof globalThis;// Which is declared as (simplified):interface Window extends GlobalEventHandlers {  // ...}// Which defines a lot of known handler eventsinterface GlobalEventHandlers {  onmousedown: ((this: GlobalEventHandlers, ev: MouseEvent) => any) | null;  // ...}\n```\n\nExample:\n```text\nwindow.onscroll = function (uiEvent) {  console.log(uiEvent.button);Property 'button' does not exist on type 'Event'.2339Property 'button' does not exist on type 'Event'.};\n```\n\nExample:\n```text\nconst handler = function (uiEvent) {  console.log(uiEvent.button); // <- OK};\n```\n\nExample:\n```text\nwindow.onscroll = function (uiEvent: any) {  console.log(uiEvent.button); // <- Now, no error is given};\n```\n\nExample:\n```text\nfunction createZoo(): Animal[] {  return [new Rhino(), new Elephant(), new Snake()];}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.364Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":51,"estimatedTokens":379}}40{"id":"doc-typescript_documentation_library_structures-0f00d9e0","source":"documentation","title":"TypeScript: Documentation - Library Structures","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html","text":"Example:\n```text\nvar fs = require(\"fs\");\n```\n\nExample:\n```text\nimport * as fs from \"fs\";\n```\n\nExample:\n```text\nvar someLib = require(\"someLib\");\n```\n\nExample:\n```text\ndefine(..., ['someLib'], function(someLib) {});\n```\n\nExample:\n```text\nconst x = require(\"foo\");// Note: calling 'x' as a functionconst y = x(42);\n```\n\nExample:\n```text\nconst x = require(\"bar\");// Note: using 'new' operator on the imported variableconst y = new x(\"hello\");\n```\n\nExample:\n```text\nconst jest = require(\"jest\");require(\"jest-matchers-files\");\n```\n\nExample:\n```text\n$(() => {  console.log(\"hello!\");});\n```\n\nExample:\n```text\n<script src=\"http://a.great.cdn.for/someLib.js\"></script>\n```\n\nExample:\n```text\nfunction createGreeting(s) {  return \"Hello, \" + s;}\n```\n\nExample:\n```text\n// Webwindow.createGreeting = function (s) {  return \"Hello, \" + s;};// Nodeglobal.createGreeting = function (s) {  return \"Hello, \" + s;};// Potentially any runtimeglobalThis.createGreeting = function (s) {  return \"Hello, \" + s;};\n```\n\nExample:\n```text\nimport moment = require(\"moment\");console.log(moment.format());\n```\n\nExample:\n```text\nconsole.log(moment.format());\n```\n\nExample:\n```text\n(function (root, factory) {    if (typeof define === \"function\" && define.amd) {        define([\"libName\"], factory);    } else if (typeof module === \"object\" && module.exports) {        module.exports = factory(require(\"libName\"));    } else {        root.returnExports = factory(root.libName);    }}(this, function (b) {\n```\n\nExample:\n```text\n/// <reference types=\"someLib\" />function getThing(): someLib.thing;\n```\n\nExample:\n```text\nimport * as moment from \"moment\";function getThing(): moment;\n```\n\nExample:\n```text\n/// <reference types=\"moment\" />function getThing(): moment;\n```\n\nExample:\n```text\nimport * as someLib from \"someLib\";\n```\n\nExample:\n```text\ndeclare namespace cats {  interface KittySettings {}}\n```\n\nExample:\n```text\n// at top-levelinterface CatsKittySettings {}\n```\n\nExample:\n```text\nimport exp = require(\"express\");var app = exp();\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.364Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":106,"estimatedTokens":506}}41{"id":"doc-typescript_documentation_global_modifying_module-52d5236d","source":"documentation","title":"TypeScript: Documentation - Global: Modifying Module","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html","text":"Example:\n```text\n// 'require' call that doesn't use its return valuevar unused = require(\"magic-string-time\");/* or */require(\"magic-string-time\");var x = \"hello, world\";// Creates new methods on built-in typesconsole.log(x.startsWithHello());var y = [1, 2, 3];// Creates new methods on built-in typesconsole.log(y.reverseAndSort());\n```\n\nExample:\n```text\n// 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 {};\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.365Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":11,"estimatedTokens":388}}42{"id":"doc-typescript_documentation_modules_theory-0ac78650","source":"documentation","title":"TypeScript: Documentation - Modules - Theory","url":"https://www.typescriptlang.org/docs/handbook/modules/theory.html","text":"Example:\n```text\n<html>  <head>    <script src=\"a.js\"></script>    <script src=\"b.js\"></script>  </head>  <body></body></html>\n```\n\nExample:\n```text\n// a.jsexport default \"Hello from a.js\";\n```\n\nExample:\n```text\n// b.jsimport a from \"./a.js\";console.log(a); // 'Hello from a.js'\n```\n\nExample:\n```text\n// a.jsexports.message = \"Hello from a.js\";\n```\n\nExample:\n```text\n// b.jsconst a = require(\"./a\");console.log(a.message); // 'Hello from a.js'\n```\n\nExample:\n```text\nimport sayHello from \"greetings\";sayHello(\"world\");\n```\n\nExample:\n```text\nimport { sayHello } from \"greetings\";sayHello(\"world\");\n```\n\nExample:\n```text\nObject.defineProperty(exports, \"__esModule\", { value: true });const greetings_1 = require(\"greetings\");(0, greetings_1.sayHello)(\"world\");\n```\n\nExample:\n```text\nimport { add } from \"./math.mjs\";add(1, 2);\n```\n\nExample:\n```text\nconst math_1 = require(\"./math.mjs\");math_1.add(1, 2);\n```\n\nExample:\n```text\nimport monkey from \"🐒\"; // Looks for './eats/bananas.js'import cow from \"🐄\";    // Looks for './eats/grass.js'import lion from \"🦁\";   // Looks for './eats/you.js'\n```\n\nExample:\n```text\n// @Filename: math.tsexport function add(a: number, b: number) {  return a + b;}// @Filename: main.tsimport { add } from \"./math\";add(1, 2);\n```\n\nExample:\n```text\n// @moduleResolution: node16// @rootDir: src// @outDir: dist// @Filename: src/math.mtsexport function add(a: number, b: number) {  return a + b;}// @Filename: src/main.mtsimport { add } from \"./math.mjs\";add(1, 2);\n```\n\nExample:\n```text\n// @Filename: src/math.tsexport function add(a: number, b: number) {  return a + b;}// @Filename: src/main.tsimport { add } from \"./math.ts\";//                  ^^^^^^^^^^^// An import path can only end with a '.ts' extension when 'allowImportingTsExtensions' is enabled.\n```\n\nExample:\n```text\nexport * from \"./utils\";\n```\n\nExample:\n```text\nError [ERR_MODULE_NOT_FOUND]: Cannot find module '.../node_modules/dependency/utils' imported from .../node_modules/dependency/index.jsDid you mean to import ./utils.js?\n```\n\nExample:\n```text\nexport * from \"./utils.js\";\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.366Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":86,"estimatedTokens":522}}43{"id":"doc-typescript_documentation_dom_manipulation-79aee076","source":"documentation","title":"TypeScript: Documentation - DOM Manipulation","url":"https://www.typescriptlang.org/docs/handbook/dom-manipulation.html","text":"Example:\n```text\n<!DOCTYPE html><html lang=\"en\">  <head><title>TypeScript Dom Manipulation</title></head>  <body>    <div id=\"app\"></div>    <!-- Assume index.js is the compiled output of index.ts -->    <script src=\"index.js\"></script>  </body></html>\n```\n\nExample:\n```text\n// 1. Select the div element using the id propertyconst app = document.getElementById(\"app\");// 2. Create a new <p></p> element programmaticallyconst p = document.createElement(\"p\");// 3. Add the text contentp.textContent = \"Hello, World!\";// 4. Append the p element to the div elementapp?.appendChild(p);\n```\n\nExample:\n```text\ngetElementById(elementId: string): HTMLElement | null;\n```\n\nExample:\n```text\ncreateElement<K extends keyof HTMLElementTagNameMap>(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;\n```\n\nExample:\n```text\ninterface HTMLElementTagNameMap {    \"a\": HTMLAnchorElement;    \"abbr\": HTMLElement;    \"address\": HTMLElement;    \"applet\": HTMLAppletElement;    \"area\": HTMLAreaElement;        ...}\n```\n\nExample:\n```text\nappendChild<T extends Node>(newChild: T): T;\n```\n\nExample:\n```text\n<div>  <p>Hello, World</p>  <p>TypeScript!</p></div>;const div = document.getElementsByTagName(\"div\")[0];div.children;// HTMLCollection(2) [p, p]div.childNodes;// NodeList(2) [p, p]\n```\n\nExample:\n```text\n<div>  <p>Hello, World</p>  TypeScript!</div>;const div = document.getElementsByTagName(\"div\")[0];div.children;// HTMLCollection(1) [p]div.childNodes;// NodeList(2) [p, text]\n```\n\nExample:\n```text\n/** * Returns the first element that is a descendant of node that matches selectors. */querySelector<K extends keyof HTMLElementTagNameMap>(selectors: K): HTMLElementTagNameMap[K] | null;querySelector<K extends keyof SVGElementTagNameMap>(selectors: K): SVGElementTagNameMap[K] | null;querySelector<E extends Element = Element>(selectors: string): E | null;/** * Returns all element descendants of node that match selectors. */querySelectorAll<K extends keyof HTMLElementTagNameMap>(selectors: K): NodeListOf<HTMLElementTagNameMap[K]>;querySelectorAll<K extends keyof SVGElementTagNameMap>(selectors: K): NodeListOf<SVGElementTagNameMap[K]>;querySelectorAll<E extends Element = Element>(selectors: string): NodeListOf<E>;\n```\n\nExample:\n```text\n<ul>  <li>First :)</li>  <li>Second!</li>  <li>Third times a charm.</li></ul>;const first = document.querySelector(\"li\"); // returns the first li elementconst all = document.querySelectorAll(\"li\"); // returns the list of all li elements\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.367Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":51,"estimatedTokens":645}}44{"id":"doc-typescript_documentation_classes-56877450","source":"documentation","title":"TypeScript: Documentation - Classes","url":"https://www.typescriptlang.org/docs/handbook/2/classes.html","text":"Example:\n```text\nclass Point {}\n```\n\nExample:\n```text\nclass Point {  x: number;  y: number;} const pt = new Point();pt.x = 0;pt.y = 0;\n```\n\nExample:\n```text\nclass Point {  x = 0;  y = 0;} const pt = new Point();// Prints 0, 0console.log(`${pt.x}, ${pt.y}`);\n```\n\nExample:\n```text\nconst pt = new Point();pt.x = \"0\";Type 'string' is not assignable to type 'number'.2322Type 'string' is not assignable to type 'number'.\n```\n\nExample:\n```text\nclass BadGreeter {  name: string;Property 'name' has no initializer and is not definitely assigned in the constructor.2564Property 'name' has no initializer and is not definitely assigned in the constructor.}\n```\n\nExample:\n```text\nclass GoodGreeter {  name: string;   constructor() {    this.name = \"hello\";  }}\n```\n\nExample:\n```text\nclass OKGreeter {  // Not initialized, but no error  name!: string;}\n```\n\nExample:\n```text\nclass Greeter {  readonly name: string = \"world\";   constructor(otherName?: string) {    if (otherName !== undefined) {      this.name = otherName;    }  }   err() {    this.name = \"not ok\";Cannot assign to 'name' because it is a read-only property.2540Cannot assign to 'name' because it is a read-only property.  }}const g = new Greeter();g.name = \"also not ok\";Cannot assign to 'name' because it is a read-only property.2540Cannot assign to 'name' because it is a read-only property.\n```\n\nExample:\n```text\nclass Point {  x: number;  y: number;   // Normal signature with defaults  constructor(x = 0, y = 0) {    this.x = x;    this.y = y;  }}\n```\n\nExample:\n```text\nclass Point {  x: number = 0;  y: number = 0;   // Constructor overloads  constructor(x: number, y: number);  constructor(xy: string);  constructor(x: string | number, y: number = 0) {    // Code logic here  }}\n```\n\nExample:\n```text\nclass Base {  k = 4;} class Derived extends Base {  constructor() {    // Prints a wrong value in ES5; throws exception in ES6    console.log(this.k);'super' must be called before accessing 'this' in the constructor of a derived class.17009'super' must be called before accessing 'this' in the constructor of a derived class.    super();  }}\n```\n\nExample:\n```text\nclass Point {  x = 10;  y = 10;   scale(n: number): void {    this.x *= n;    this.y *= n;  }}\n```\n\nExample:\n```text\nlet x: number = 0; class C {  x: string = \"hello\";   m() {    // This is trying to modify 'x' from line 1, not the class property    x = \"world\";Type 'string' is not assignable to type 'number'.2322Type 'string' is not assignable to type 'number'.  }}\n```\n\nExample:\n```text\nclass C {  _length = 0;  get length() {    return this._length;  }  set length(value) {    this._length = value;  }}\n```\n\nExample:\n```text\nclass Thing {  _size = 0;   get size(): number {    return this._size;  }   set size(value: string | number | boolean) {    let num = Number(value);     // Don't allow NaN, Infinity, etc     if (!Number.isFinite(num)) {      this._size = 0;      return;    }     this._size = num;  }}\n```\n\nExample:\n```text\nclass MyClass {  [s: string]: boolean | ((s: string) => boolean);   check(s: string) {    return this[s] as boolean;  }}\n```\n\nExample:\n```text\ninterface Pingable {  ping(): void;} class Sonar implements Pingable {  ping() {    console.log(\"ping!\");  }} class Ball implements Pingable {Class 'Ball' incorrectly implements interface 'Pingable'.\n  Property 'ping' is missing in type 'Ball' but required in type 'Pingable'.2420Class 'Ball' incorrectly implements interface 'Pingable'.\n  Property 'ping' is missing in type 'Ball' but required in type 'Pingable'.  pong() {    console.log(\"pong!\");  }}\n```\n\nExample:\n```text\ninterface Checkable {  check(name: string): boolean;} class NameChecker implements Checkable {  check(s) {Parameter 's' implicitly has an 'any' type.7006Parameter 's' implicitly has an 'any' type.    // Notice no error here    return s.toLowerCase() === \"ok\";                 any  }}\n```\n\nExample:\n```text\ninterface A {  x: number;  y?: number;}class C implements A {  x = 0;}const c = new C();c.y = 10;Property 'y' does not exist on type 'C'.2339Property 'y' does not exist on type 'C'.\n```\n\nExample:\n```text\nclass Animal {  move() {    console.log(\"Moving along!\");  }} class Dog extends Animal {  woof(times: number) {    for (let i = 0; i < times; i++) {      console.log(\"woof!\");    }  }} const d = new Dog();// Base class methodd.move();// Derived class methodd.woof(3);\n```\n\nExample:\n```text\nclass Base {  greet() {    console.log(\"Hello, world!\");  }} class Derived extends Base {  greet(name?: string) {    if (name === undefined) {      super.greet();    } else {      console.log(`Hello, ${name.toUpperCase()}`);    }  }} const d = new Derived();d.greet();d.greet(\"reader\");\n```\n\nExample:\n```text\n// Alias the derived instance through a base class referenceconst b: Base = d;// No problemb.greet();\n```\n\nExample:\n```text\nclass Base {  greet() {    console.log(\"Hello, world!\");  }} class Derived extends Base {  // Make this parameter required  greet(name: string) {Property 'greet' in type 'Derived' is not assignable to the same property in base type 'Base'.\n  Type '(name: string) => void' is not assignable to type '() => void'.\n    Target signature provides too few arguments. Expected 1 or more, but got 0.2416Property 'greet' in type 'Derived' is not assignable to the same property in base type 'Base'.\n  Type '(name: string) => void' is not assignable to type '() => void'.\n    Target signature provides too few arguments. Expected 1 or more, but got 0.    console.log(`Hello, ${name.toUpperCase()}`);  }}\n```\n\nExample:\n```text\nconst b: Base = new Derived();// Crashes because \"name\" will be undefinedb.greet();\n```\n\nExample:\n```text\ninterface Animal {  dateOfBirth: any;} interface Dog extends Animal {  breed: any;} class AnimalHouse {  resident: Animal;  constructor(animal: Animal) {    this.resident = animal;  }} class DogHouse extends AnimalHouse {  // Does not emit JavaScript code,  // only ensures the types are correct  declare resident: Dog;  constructor(dog: Dog) {    super(dog);  }}\n```\n\nExample:\n```text\nclass Base {  name = \"base\";  constructor() {    console.log(\"My name is \" + this.name);  }} class Derived extends Base {  name = \"derived\";} // Prints \"base\", not \"derived\"const d = new Derived();\n```\n\nExample:\n```text\nclass MsgError extends Error {  constructor(m: string) {    super(m);  }  sayHello() {    return \"hello \" + this.message;  }}\n```\n\nExample:\n```text\nclass MsgError extends Error {  constructor(m: string) {    super(m);     // Set the prototype explicitly.    Object.setPrototypeOf(this, MsgError.prototype);  }   sayHello() {    return \"hello \" + this.message;  }}\n```\n\nExample:\n```text\nclass Greeter {  public greet() {    console.log(\"hi!\");  }}const g = new Greeter();g.greet();\n```\n\nExample:\n```text\nclass Greeter {  public greet() {    console.log(\"Hello, \" + this.getName());  }  protected getName() {    return \"hi\";  }} class SpecialGreeter extends Greeter {  public howdy() {    // OK to access protected member here    console.log(\"Howdy, \" + this.getName());  }}const g = new SpecialGreeter();g.greet(); // OKg.getName();Property 'getName' is protected and only accessible within class 'Greeter' and its subclasses.2445Property 'getName' is protected and only accessible within class 'Greeter' and its subclasses.\n```\n\nExample:\n```text\nclass Base {  protected m = 10;}class Derived extends Base {  // No modifier, so default is 'public'  m = 15;}const d = new Derived();console.log(d.m); // OK\n```\n\nExample:\n```text\nclass Base {  protected x: number = 1;}class Derived1 extends Base {  protected x: number = 5;}class Derived2 extends Base {  f1(other: Derived2) {    other.x = 10;  }  f2(other: Derived1) {    other.x = 10;Property 'x' is protected and only accessible within class 'Derived1' and its subclasses.2445Property 'x' is protected and only accessible within class 'Derived1' and its subclasses.  }}\n```\n\nExample:\n```text\nclass Base {  private x = 0;}const b = new Base();// Can't access from outside the classconsole.log(b.x);Property 'x' is private and only accessible within class 'Base'.2341Property 'x' is private and only accessible within class 'Base'.\n```\n\nExample:\n```text\nclass Derived extends Base {  showX() {    // Can't access in subclasses    console.log(this.x);Property 'x' is private and only accessible within class 'Base'.2341Property 'x' is private and only accessible within class 'Base'.  }}\n```\n\nExample:\n```text\nclass Base {  private x = 0;}class Derived extends Base {Class 'Derived' incorrectly extends base class 'Base'.\n  Property 'x' is private in type 'Base' but not in type 'Derived'.2415Class 'Derived' incorrectly extends base class 'Base'.\n  Property 'x' is private in type 'Base' but not in type 'Derived'.  x = 1;}\n```\n\nExample:\n```text\nclass A {  private x = 10;   public sameAs(other: A) {    // No error    return other.x === this.x;  }}\n```\n\nExample:\n```text\nclass MySafe {  private secretKey = 12345;}\n```\n\nExample:\n```text\n// In a JavaScript file...const s = new MySafe();// Will print 12345console.log(s.secretKey);\n```\n\nExample:\n```text\nclass MySafe {  private secretKey = 12345;} const s = new MySafe(); // Not allowed during type checkingconsole.log(s.secretKey);Property 'secretKey' is private and only accessible within class 'MySafe'.2341Property 'secretKey' is private and only accessible within class 'MySafe'. // OKconsole.log(s[\"secretKey\"]);\n```\n\nExample:\n```text\nclass Dog {  #barkAmount = 0;  personality = \"happy\";   constructor() {}}\n```\n\nExample:\n```text\n\"use strict\";class Dog {    #barkAmount = 0;    personality = \"happy\";    constructor() { }}\n```\n\nExample:\n```text\n\"use strict\";var _Dog_barkAmount;class Dog {    constructor() {        _Dog_barkAmount.set(this, 0);        this.personality = \"happy\";    }}_Dog_barkAmount = new WeakMap();\n```\n\nExample:\n```text\nclass MyClass {  static x = 0;  static printX() {    console.log(MyClass.x);  }}console.log(MyClass.x);MyClass.printX();\n```\n\nExample:\n```text\nclass MyClass {  private static x = 0;}console.log(MyClass.x);Property 'x' is private and only accessible within class 'MyClass'.2341Property 'x' is private and only accessible within class 'MyClass'.\n```\n\nExample:\n```text\nclass Base {  static getGreeting() {    return \"Hello world\";  }}class Derived extends Base {  myGreeting = Derived.getGreeting();}\n```\n\nExample:\n```text\nclass S {  static name = \"S!\";Static property 'name' conflicts with built-in property 'Function.name' of constructor function 'S'.2699Static property 'name' conflicts with built-in property 'Function.name' of constructor function 'S'.}\n```\n\nExample:\n```text\n// Unnecessary \"static\" classclass MyStaticClass {  static doSomething() {}} // Preferred (alternative 1)function doSomething() {} // Preferred (alternative 2)const MyHelperObject = {  dosomething() {},};\n```\n\nExample:\n```text\nclass Foo {    static #count = 0;     get count() {        return Foo.#count;    }     static {        try {            const lastInstances = loadLastInstances();            Foo.#count += lastInstances.length;        }        catch {}    }}\n```\n\nExample:\n```text\nclass Box<Type> {  contents: Type;  constructor(value: Type) {    this.contents = value;  }} const b = new Box(\"hello!\");     const b: Box<string>\n```\n\nExample:\n```text\nclass Box<Type> {  static defaultValue: Type;Static members cannot reference class type parameters.2302Static members cannot reference class type parameters.}\n```\n\nExample:\n```text\nclass MyClass {  name = \"MyClass\";  getName() {    return this.name;  }}const c = new MyClass();const obj = {  name: \"obj\",  getName: c.getName,}; // Prints \"obj\", not \"MyClass\"console.log(obj.getName());\n```\n\nExample:\n```text\nclass MyClass {  name = \"MyClass\";  getName = () => {    return this.name;  };}const c = new MyClass();const g = c.getName;// Prints \"MyClass\" instead of crashingconsole.log(g());\n```\n\nExample:\n```text\n// TypeScript input with 'this' parameterfunction fn(this: SomeType, x: number) {  /* ... */}\n```\n\nExample:\n```text\n// JavaScript outputfunction fn(x) {  /* ... */}\n```\n\nExample:\n```text\nclass MyClass {  name = \"MyClass\";  getName(this: MyClass) {    return this.name;  }}const c = new MyClass();// OKc.getName(); // Error, would crashconst g = c.getName;console.log(g());The 'this' context of type 'void' is not assignable to method's 'this' of type 'MyClass'.2684The 'this' context of type 'void' is not assignable to method's 'this' of type 'MyClass'.\n```\n\nExample:\n```text\nclass Box {  contents: string = \"\";  set(value: string) {  (method) Box.set(value: string): this    this.contents = value;    return this;  }}\n```\n\nExample:\n```text\nclass ClearableBox extends Box {  clear() {    this.contents = \"\";  }} const a = new ClearableBox();const b = a.set(\"hello\");     const b: ClearableBox\n```\n\nExample:\n```text\nclass Box {  content: string = \"\";  sameAs(other: this) {    return other.content === this.content;  }}\n```\n\nExample:\n```text\nclass Box {  content: string = \"\";  sameAs(other: this) {    return other.content === this.content;  }} class DerivedBox extends Box {  otherContent: string = \"?\";} const base = new Box();const derived = new DerivedBox();derived.sameAs(base);Argument of type 'Box' is not assignable to parameter of type 'DerivedBox'.\n  Property 'otherContent' is missing in type 'Box' but required in type 'DerivedBox'.2345Argument of type 'Box' is not assignable to parameter of type 'DerivedBox'.\n  Property 'otherContent' is missing in type 'Box' but required in type 'DerivedBox'.\n```\n\nExample:\n```text\nclass FileSystemObject {  isFile(): this is FileRep {    return this instanceof FileRep;  }  isDirectory(): this is Directory {    return this instanceof Directory;  }  isNetworked(): this is Networked & this {    return this.networked;  }  constructor(public path: string, private networked: boolean) {}} class FileRep extends FileSystemObject {  constructor(path: string, public content: string) {    super(path, false);  }} class Directory extends FileSystemObject {  children: FileSystemObject[];} interface Networked {  host: string;} const fso: FileSystemObject = new FileRep(\"foo/bar.txt\", \"foo\"); if (fso.isFile()) {  fso.content;  const fso: FileRep} else if (fso.isDirectory()) {  fso.children;  const fso: Directory} else if (fso.isNetworked()) {  fso.host;  const fso: Networked & FileSystemObject}\n```\n\nExample:\n```text\nclass Box<T> {  value?: T;   hasValue(): this is { value: T } {    return this.value !== undefined;  }} const box = new Box<string>();box.value = \"Gameboy\"; box.value;     (property) Box<string>.value?: string if (box.hasValue()) {  box.value;       (property) value: string}\n```\n\nExample:\n```text\nclass Params {  constructor(    public readonly x: number,    protected y: number,    private z: number  ) {    // No body necessary  }}const a = new Params(1, 2, 3);console.log(a.x);             (property) Params.x: numberconsole.log(a.z);Property 'z' is private and only accessible within class 'Params'.2341Property 'z' is private and only accessible within class 'Params'.\n```\n\nExample:\n```text\nconst someClass = class<Type> {  content: Type;  constructor(value: Type) {    this.content = value;  }}; const m = new someClass(\"Hello, world\");     const m: someClass<string>\n```\n\nExample:\n```text\nclass Point {  createdAt: number;  x: number;  y: number  constructor(x: number, y: number) {    this.createdAt = Date.now()    this.x = x;    this.y = y;  }}type PointInstance = InstanceType<typeof Point> function moveRight(point: PointInstance) {  point.x += 5;} const point = new Point(3, 4);moveRight(point);point.x; // => 8\n```\n\nExample:\n```text\nabstract class Base {  abstract getName(): string;   printName() {    console.log(\"Hello, \" + this.getName());  }} const b = new Base();Cannot create an instance of an abstract class.2511Cannot create an instance of an abstract class.\n```\n\nExample:\n```text\nclass Derived extends Base {  getName() {    return \"world\";  }} const d = new Derived();d.printName();\n```\n\nExample:\n```text\nclass Derived extends Base {Non-abstract class 'Derived' does not implement inherited abstract member getName from class 'Base'.2515Non-abstract class 'Derived' does not implement inherited abstract member getName from class 'Base'.  // forgot to do anything}\n```\n\nExample:\n```text\nfunction greet(ctor: typeof Base) {  const instance = new ctor();Cannot create an instance of an abstract class.2511Cannot create an instance of an abstract class.  instance.printName();}\n```\n\nExample:\n```text\n// Bad!greet(Base);\n```\n\nExample:\n```text\nfunction greet(ctor: new () => Base) {  const instance = new ctor();  instance.printName();}greet(Derived);greet(Base);Argument of type 'typeof Base' is not assignable to parameter of type 'new () => Base'.\n  Cannot assign an abstract constructor type to a non-abstract constructor type.2345Argument of type 'typeof Base' is not assignable to parameter of type 'new () => Base'.\n  Cannot assign an abstract constructor type to a non-abstract constructor type.\n```\n\nExample:\n```text\nclass Point1 {  x = 0;  y = 0;} class Point2 {  x = 0;  y = 0;} // OKconst p: Point1 = new Point2();\n```\n\nExample:\n```text\nclass Person {  name: string;  age: number;} class Employee {  name: string;  age: number;  salary: number;} // OKconst p: Person = new Employee();\n```\n\nExample:\n```text\nclass Empty {} function fn(x: Empty) {  // can't do anything with 'x', so I won't} // All OK!fn(window);fn({});fn(fn);\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.369Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":73,"totalLines":378,"estimatedTokens":4345}}45{"id":"doc-typescript_documentation_js_projects_utilizing_t-644e079c","source":"documentation","title":"TypeScript: Documentation - JS Projects Utilizing TypeScript","url":"https://www.typescriptlang.org/docs/handbook/intro-to-js-ts.html","text":"Example:\n```text\n/** @type {number} */var x; x = 0; // OKx = false; // OK?!\n```\n\nExample:\n```text\n// @ts-check/** @type {number} */var x; x = 0; // OKx = false; // Not OKType 'boolean' is not assignable to type 'number'.2322Type 'boolean' is not assignable to type 'number'.\n```\n\nExample:\n```text\n// @ts-check/** @type {number} */var x; x = 0; // OK// @ts-expect-errorx = false; // Not OK\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.369Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":16,"estimatedTokens":102}}46{"id":"doc-typescript_documentation_module_class-1cf6df93","source":"documentation","title":"TypeScript: Documentation - Module: Class","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-class-d-ts.html","text":"Example:\n```text\nconst Greeter = require(\"super-greeter\");const greeter = new Greeter();greeter.greet();\n```\n\nExample:\n```text\n// 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 myClassLib;/*~ 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;  }}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.369Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":11,"estimatedTokens":527}}47{"id":"doc-typescript_documentation_consumption-16bedb9c","source":"documentation","title":"TypeScript: Documentation - Consumption","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html","text":"Example:\n```text\nnpm install --save-dev @types/lodash\n```\n\nExample:\n```text\nimport * as _ from \"lodash\";_.padStart(\"Hello TypeScript!\", 20, \" \");\n```\n\nExample:\n```text\n_.padStart(\"Hello TypeScript!\", 20, \" \");\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.369Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":16,"estimatedTokens":57}}48{"id":"doc-typescript_documentation_variable_declaration-22717b86","source":"documentation","title":"TypeScript: Documentation - Variable Declaration","url":"https://www.typescriptlang.org/docs/handbook/variable-declarations.html","text":"Example:\n```text\nvar a = 10;\n```\n\nExample:\n```text\nfunction f() {  var message = \"Hello, world!\";  return message;}\n```\n\nExample:\n```text\nfunction f() {  var a = 10;  return function g() {    var b = a + 1;    return b;  };}var g = f();g(); // returns '11'\n```\n\nExample:\n```text\nfunction f() {  var a = 1;  a = 2;  var b = g();  a = 3;  return b;  function g() {    return a;  }}f(); // returns '2'\n```\n\nExample:\n```text\nfunction f(shouldInitialize: boolean) {  if (shouldInitialize) {    var x = 10;  }  return x;}f(true); // returns '10'f(false); // returns 'undefined'\n```\n\nExample:\n```text\nfunction sumMatrix(matrix: number[][]) {  var sum = 0;  for (var i = 0; i < matrix.length; i++) {    var currentRow = matrix[i];    for (var i = 0; i < currentRow.length; i++) {      sum += currentRow[i];    }  }  return sum;}\n```\n\nExample:\n```text\nfor (var i = 0; i < 10; i++) {  setTimeout(function () {    console.log(i);  }, 100 * i);}\n```\n\nExample:\n```text\n10101010101010101010\n```\n\nExample:\n```text\n0123456789\n```\n\nExample:\n```text\nfor (var i = 0; i < 10; i++) {  // capture the current state of 'i'  // by invoking a function with its current value  (function (i) {    setTimeout(function () {      console.log(i);    }, 100 * i);  })(i);}\n```\n\nExample:\n```text\nlet hello = \"Hello!\";\n```\n\nExample:\n```text\nfunction f(input: boolean) {  let a = 100;  if (input) {    // Still okay to reference 'a'    let b = a + 1;    return b;  }  // Error: 'b' doesn't exist here  return b;}\n```\n\nExample:\n```text\ntry {  throw \"oh no!\";} catch (e) {  console.log(\"Oh well.\");}// Error: 'e' doesn't exist hereconsole.log(e);\n```\n\nExample:\n```text\na++; // illegal to use 'a' before it's declared;let a;\n```\n\nExample:\n```text\nfunction foo() {  // okay to capture 'a'  return a;}// illegal call 'foo' before 'a' is declared// runtimes should throw an error herefoo();let a;\n```\n\nExample:\n```text\nfunction f(x) {  var x;  var x;  if (true) {    var x;  }}\n```\n\nExample:\n```text\nlet x = 10;let x = 20; // error: can't re-declare 'x' in the same scope\n```\n\nExample:\n```text\nfunction f(x) {  let x = 100; // error: interferes with parameter declaration}function g() {  let x = 100;  var x = 100; // error: can't have both declarations of 'x'}\n```\n\nExample:\n```text\nfunction f(condition, x) {  if (condition) {    let x = 100;    return x;  }  return x;}f(false, 0); // returns '0'f(true, 0); // returns '100'\n```\n\nExample:\n```text\nfunction sumMatrix(matrix: number[][]) {  let sum = 0;  for (let i = 0; i < matrix.length; i++) {    var currentRow = matrix[i];    for (let i = 0; i < currentRow.length; i++) {      sum += currentRow[i];    }  }  return sum;}\n```\n\nExample:\n```text\nfunction theCityThatAlwaysSleeps() {  let getCity;  if (true) {    let city = \"Seattle\";    getCity = function () {      return city;    };  }  return getCity();}\n```\n\nExample:\n```text\nfor (let i = 0; i < 10; i++) {  setTimeout(function () {    console.log(i);  }, 100 * i);}\n```\n\nExample:\n```text\nconst numLivesForCat = 9;\n```\n\nExample:\n```text\nconst numLivesForCat = 9;const kitty = {  name: \"Aurora\",  numLives: numLivesForCat,};// Errorkitty = {  name: \"Danielle\",  numLives: numLivesForCat,};// all \"okay\"kitty.name = \"Rory\";kitty.name = \"Kitty\";kitty.name = \"Cat\";kitty.numLives--;\n```\n\nExample:\n```text\nlet input = [1, 2];let [first, second] = input;console.log(first); // outputs 1console.log(second); // outputs 2\n```\n\nExample:\n```text\nfirst = input[0];second = input[1];\n```\n\nExample:\n```text\n// swap variables[first, second] = [second, first];\n```\n\nExample:\n```text\nfunction f([first, second]: [number, number]) {  console.log(first);  console.log(second);}f([1, 2]);\n```\n\nExample:\n```text\nlet [first, ...rest] = [1, 2, 3, 4];console.log(first); // outputs 1console.log(rest); // outputs [ 2, 3, 4 ]\n```\n\nExample:\n```text\nlet [first] = [1, 2, 3, 4];console.log(first); // outputs 1\n```\n\nExample:\n```text\nlet [, second, , fourth] = [1, 2, 3, 4];console.log(second); // outputs 2console.log(fourth); // outputs 4\n```\n\nExample:\n```text\nlet tuple: [number, string, boolean] = [7, \"hello\", true];let [a, b, c] = tuple; // a: number, b: string, c: boolean\n```\n\nExample:\n```text\nlet [a, b, c, d] = tuple; // Error, no element at index 3\n```\n\nExample:\n```text\nlet [a, ...bc] = tuple; // bc: [string, boolean]let [a, b, c, ...d] = tuple; // d: [], the empty tuple\n```\n\nExample:\n```text\nlet [a] = tuple; // a: numberlet [, b] = tuple; // b: string\n```\n\nExample:\n```text\nlet o = {  a: \"foo\",  b: 12,  c: \"bar\",};let { a, b } = o;\n```\n\nExample:\n```text\n({ a, b } = { a: \"baz\", b: 101 });\n```\n\nExample:\n```text\nlet { a, ...passthrough } = o;let total = passthrough.b + passthrough.c.length;\n```\n\nExample:\n```text\nlet { a: newName1, b: newName2 } = o;\n```\n\nExample:\n```text\nlet newName1 = o.a;let newName2 = o.b;\n```\n\nExample:\n```text\nlet { a: newName1, b: newName2 }: { a: string; b: number } = o;\n```\n\nExample:\n```text\nfunction keepWholeObject(wholeObject: { a: string; b?: number }) {  let { a, b = 1001 } = wholeObject;}\n```\n\nExample:\n```text\ntype C = { a: string; b?: number };function f({ a, b }: C): void {  // ...}\n```\n\nExample:\n```text\nfunction f({ a = \"\", b = 0 } = {}): void {  // ...}f();\n```\n\nExample:\n```text\nfunction f({ a, b = 0 } = { a: \"\" }): void {  // ...}f({ a: \"yes\" }); // ok, default b = 0f(); // ok, default to { a: \"\" }, which then defaults b = 0f({}); // error, 'a' is required if you supply an argument\n```\n\nExample:\n```text\nlet first = [1, 2];let second = [3, 4];let bothPlus = [0, ...first, ...second, 5];\n```\n\nExample:\n```text\nlet defaults = { food: \"spicy\", price: \"$$\", ambiance: \"noisy\" };let search = { ...defaults, food: \"rich\" };\n```\n\nExample:\n```text\nlet defaults = { food: \"spicy\", price: \"$$\", ambiance: \"noisy\" };let search = { food: \"rich\", ...defaults };\n```\n\nExample:\n```text\nclass C {  p = 12;  m() {}}let c = new C();let clone = { ...c };clone.p; // okclone.m(); // error!\n```\n\nExample:\n```text\nfunction f() {  using x = new C();  doSomethingWith(x);} // `x[Symbol.dispose]()` is called\n```\n\nExample:\n```text\nfunction f() {  const x = new C();  try {    doSomethingWith(x);  }  finally {    x[Symbol.dispose]();  }}\n```\n\nExample:\n```text\n{  using file = await openFile();  file.write(text);  doSomethingThatMayThrow();} // `file` is disposed, even if an error is thrown\n```\n\nExample:\n```text\nfunction f() {  using activity = new TraceActivity(\"f\"); // traces entry into function  // ...} // traces exit of function\n```\n\nExample:\n```text\n{  using x = b ? new C() : null;  // ...}\n```\n\nExample:\n```text\n{  const x = b ? new C() : null;  try {    // ...  }  finally {    x?.[Symbol.dispose]();  }}\n```\n\nExample:\n```text\n// from the default lib:interface Disposable {  [Symbol.dispose](): void;}// usage:class TraceActivity implements Disposable {  readonly name: string;  constructor(name: string) {    this.name = name;    console.log(`Entering: ${name}`);  }  [Symbol.dispose](): void {    console.log(`Exiting: ${name}`);  }}function f() {  using _activity = new TraceActivity(\"f\");  console.log(\"Hello world!\");}f();// prints://   Entering: f//   Hello world!//   Exiting: f\n```\n\nExample:\n```text\nasync function f() {  await using x = new C();} // `await x[Symbol.asyncDispose]()` is invoked\n```\n\nExample:\n```text\n// from the default lib:interface AsyncDisposable {  [Symbol.asyncDispose]: PromiseLike<void>;}// usage:class DatabaseTransaction implements AsyncDisposable {  public success = false;  private db: Database | undefined;  private constructor(db: Database) {    this.db = db;  }  static async create(db: Database) {    await db.execAsync(\"BEGIN TRANSACTION\");    return new DatabaseTransaction(db);  }  async [Symbol.asyncDispose]() {    if (this.db) {      const db = this.db:      this.db = undefined;      if (this.success) {        await db.execAsync(\"COMMIT TRANSACTION\");      }      else {        await db.execAsync(\"ROLLBACK TRANSACTION\");      }    }  }}async function transfer(db: Database, account1: Account, account2: Account, amount: number) {  using tx = await DatabaseTransaction.create(db);  if (await debitAccount(db, account1, amount)) {    await creditAccount(db, account2, amount);  }  // if an exception is thrown before this line, the transaction will roll back  tx.success = true;  // now the transaction will commit}\n```\n\nExample:\n```text\n{  await using x = getResourceSynchronously();} // performs `await x[Symbol.asyncDispose]()`{  await using y = await getResourceAsynchronously();} // performs `await y[Symbol.asyncDispose]()`\n```\n\nExample:\n```text\nfunction g() {  return Promise.reject(\"error!\");}async function f() {  await using x = new C();  return g(); // missing an `await`}\n```\n\nExample:\n```text\nasync function f() {  try {    return g(); // also reports an unhandled rejection  }  finally {    await somethingElse();  }}\n```\n\nExample:\n```text\nasync function f() {  await using x = new C();  return await g();}\n```\n\nExample:\n```text\nfor (using x = getReader(); !x.eof; x.next()) {  // ...}\n```\n\nExample:\n```text\nfunction * g() {  yield createResource1();  yield createResource2();}for (using x of g()) {  // ...}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.372Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":64,"totalLines":321,"estimatedTokens":2270}}49{"id":"doc-typescript_documentation_module_function-6c4460fc","source":"documentation","title":"TypeScript: Documentation - Module: Function","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html","text":"Example:\n```text\nimport greeter from \"super-greeter\";greeter(2);greeter(\"Hello world\");\n```\n\nExample:\n```text\n// 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;}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.372Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":11,"estimatedTokens":645}}50{"id":"doc-typescript_documentation_global_d_ts-037050ec","source":"documentation","title":"TypeScript: Documentation - Global .d.ts","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-d-ts.html","text":"Example:\n```text\n$(() => {  console.log(\"hello!\");});\n```\n\nExample:\n```text\n<script src=\"http://a.great.cdn.for/someLib.js\"></script>\n```\n\nExample:\n```text\nfunction createGreeting(s) {  return \"Hello, \" + s;}\n```\n\nExample:\n```text\nwindow.createGreeting = function (s) {  return \"Hello, \" + s;};\n```\n\nExample:\n```text\n// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]// Project: [~THE PROJECT NAME~]// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>/*~ If this library is callable (e.g. can be invoked as myLib(3)), *~ include those call signatures here. *~ Otherwise, delete this section. */declare function myLib(a: string): string;declare function myLib(a: number): number;/*~ If you want the name of this library to be a valid type name, *~ you can do so here. *~ *~ For example, this allows us to write 'var x: myLib'; *~ Be sure this actually makes sense! If it doesn't, just *~ delete this declaration and add types inside the namespace below. */interface myLib {  name: string;  length: number;  extras?: string[];}/*~ If your library has properties exposed on a global variable, *~ place them here. *~ You should also place types (interfaces and type alias) here. */declare namespace myLib {  //~ We can write 'myLib.timeout = 50;'  let timeout: number;  //~ We can access 'myLib.version', but not change it  const version: string;  //~ There's some class we can create via 'let c = new myLib.Cat(42)'  //~ Or reference e.g. 'function f(c: myLib.Cat) { ... }  class Cat {    constructor(n: number);    //~ We can read 'c.age' from a 'Cat' instance    readonly age: number;    //~ We can invoke 'c.purr()' from a 'Cat' instance    purr(): void;  }  //~ We can declare a variable as  //~   'var s: myLib.CatSettings = { weight: 5, name: \"Maru\" };'  interface CatSettings {    weight: number;    name: string;    tailLength?: number;  }  //~ We can write 'const v: myLib.VetID = 42;'  //~  or 'const v: myLib.VetID = \"bob\";'  type VetID = string | number;  //~ We can invoke 'myLib.checkCat(c)' or 'myLib.checkCat(c, v);'  function checkCat(c: Cat, s?: VetID);}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.372Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":26,"estimatedTokens":528}}51{"id":"doc-typescript_documentation_what_is_a_tsconfig_json-328e8c22","source":"documentation","title":"TypeScript: Documentation - What is a tsconfig.json","url":"https://www.typescriptlang.org/docs/handbook/tsconfig-json.html","text":"Example:\n```typescript\n{  \"compilerOptions\": {    \"module\": \"commonjs\",    \"noImplicitAny\": true,    \"removeComments\": true,    \"preserveConstEnums\": true,    \"sourceMap\": true  },  \"files\": [    \"core.ts\",    \"sys.ts\",    \"types.ts\",    \"scanner.ts\",    \"parser.ts\",    \"utilities.ts\",    \"binder.ts\",    \"checker.ts\",    \"emitter.ts\",    \"program.ts\",    \"commandLineParser.ts\",    \"tsc.ts\",    \"diagnosticInformationMap.generated.ts\"  ]}\n```\n\nExample:\n```typescript\n{  \"compilerOptions\": {    \"module\": \"system\",    \"noImplicitAny\": true,    \"removeComments\": true,    \"preserveConstEnums\": true,    \"outFile\": \"../../built/local/tsc.js\",    \"sourceMap\": true  },  \"include\": [\"src/**/*\"],  \"exclude\": [\"**/*.spec.ts\"]}\n```\n\nExample:\n```typescript\n{  \"extends\": \"@tsconfig/node12/tsconfig.json\",  \"compilerOptions\": {    \"preserveConstEnums\": true  },  \"include\": [\"src/**/*\"],  \"exclude\": [\"**/*.spec.ts\"]}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.373Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":16,"estimatedTokens":232}}52{"id":"doc-typescript_documentation_publishing-2867a7ff","source":"documentation","title":"TypeScript: Documentation - Publishing","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html","text":"Example:\n```text\n{  \"name\": \"awesome\",  \"author\": \"Vandelay Industries\",  \"version\": \"1.0.0\",  \"main\": \"./lib/main.js\",  \"types\": \"./lib/main.d.ts\"}\n```\n\nExample:\n```text\n{  \"name\": \"browserify-typescript-extension\",  \"author\": \"Vandelay Industries\",  \"version\": \"1.0.0\",  \"main\": \"./lib/main.js\",  \"types\": \"./lib/main.d.ts\",  \"dependencies\": {    \"browserify\": \"latest\",    \"@types/browserify\": \"latest\",    \"typescript\": \"next\"  }}\n```\n\nExample:\n```text\n/// <reference path=\"../typescript/lib/typescriptServices.d.ts\" />....\n```\n\nExample:\n```text\n/// <reference types=\"typescript\" />....\n```\n\nExample:\n```text\n{  \"name\": \"package-name\",  \"version\": \"1.0.0\",  \"types\": \"./index.d.ts\",  \"typesVersions\": {    \">=3.1\": { \"*\": [\"ts3.1/*\"] }  }}\n```\n\nExample:\n```text\n{  \"name\": \"package-name\",  \"version\": \"1.0.0\",  \"types\": \"./index.d.ts\",  \"typesVersions\": {    \"<4.0\": { \"index.d.ts\": [\"index.v3.d.ts\"] }  }}\n```\n\nExample:\n```typescript\n{  \"name\": \"package-name\",  \"version\": \"1.0\",  \"types\": \"./index.d.ts\",  \"typesVersions\": {    \">=3.2\": { \"*\": [\"ts3.2/*\"] },    \">=3.1\": { \"*\": [\"ts3.1/*\"] }  }}\n```\n\nExample:\n```typescript\n{  \"name\": \"package-name\",  \"version\": \"1.0\",  \"types\": \"./index.d.ts\",  \"typesVersions\": {    // NOTE: this doesn't work!    \">=3.1\": { \"*\": [\"ts3.1/*\"] },    \">=3.2\": { \"*\": [\"ts3.2/*\"] }  }}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.373Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":41,"estimatedTokens":336}}53{"id":"doc-typescript_documentation_module_plugin-53bcc605","source":"documentation","title":"TypeScript: Documentation - Module: Plugin","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-plugin-d-ts.html","text":"Example:\n```text\nimport { greeter } from \"super-greeter\";// Normal Greeter APIgreeter(2);greeter(\"Hello world\");// Now we extend the object with a new function at runtimeimport \"hyper-super-greeter\";greeter.hyperGreet();\n```\n\nExample:\n```text\n/*~ 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;\n```\n\nExample:\n```text\n// 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;  }}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.373Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":16,"estimatedTokens":332}}54{"id":"doc-typescript_documentation_creating_d_ts_files_fro-5db98ae1","source":"documentation","title":"TypeScript: Documentation - Creating .d.ts Files from .js files","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html","text":"Example:\n```typescript\n{  // Change this to match your project  \"include\": [\"src/**/*\"],  \"compilerOptions\": {    // Tells TypeScript to read JS files, as    // normally they are ignored as source files    \"allowJs\": true,    // Generate d.ts files    \"declaration\": true,    // This compiler run should    // only output d.ts files    \"emitDeclarationOnly\": true,    // Types should go into this directory.    // Removing this would place the .d.ts files    // next to the .js files    \"outDir\": \"dist\",    // go to js file when using IDE functions like    // \"Go to Definition\" in VSCode    \"declarationMap\": true  }}\n```\n\nExample:\n```text\nnpx -p typescript tsc src/**/*.js --declaration --allowJs --emitDeclarationOnly --outDir types\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.374Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":11,"estimatedTokens":189}}55{"id":"doc-typescript_documentation_do_s_and_don_ts-a0f6c99d","source":"documentation","title":"TypeScript: Documentation - Do's and Don'ts","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html","text":"Example:\n```text\n/* WRONG */function reverse(s: String): String;\n```\n\nExample:\n```text\n/* OK */function reverse(s: string): string;\n```\n\nExample:\n```text\n/* WRONG */function fn(x: () => any) {  x();}\n```\n\nExample:\n```text\n/* OK */function fn(x: () => void) {  x();}\n```\n\nExample:\n```text\nfunction fn(x: () => void) {  var k = x(); // oops! meant to do something else  k.doSomething(); // error, but would be OK if the return type had been 'any'}\n```\n\nExample:\n```text\n/* WRONG */interface Fetcher {  getObject(done: (data: unknown, elapsedTime?: number) => void): void;}\n```\n\nExample:\n```text\n/* OK */interface Fetcher {  getObject(done: (data: unknown, elapsedTime: number) => void): void;}\n```\n\nExample:\n```text\n/* WRONG */declare function beforeAll(action: () => void, timeout?: number): void;declare function beforeAll(  action: (done: DoneFn) => void,  timeout?: number): void;\n```\n\nExample:\n```text\n/* OK */declare function beforeAll(  action: (done: DoneFn) => void,  timeout?: number): void;\n```\n\nExample:\n```text\n/* WRONG */declare function fn(x: unknown): unknown;declare function fn(x: HTMLElement): number;declare function fn(x: HTMLDivElement): string;var myElem: HTMLDivElement;var x = fn(myElem); // x: unknown, wat?\n```\n\nExample:\n```text\n/* OK */declare function fn(x: HTMLDivElement): string;declare function fn(x: HTMLElement): number;declare function fn(x: unknown): unknown;var myElem: HTMLDivElement;var x = fn(myElem); // x: string, :)\n```\n\nExample:\n```text\n/* WRONG */interface Example {  diff(one: string): number;  diff(one: string, two: string): number;  diff(one: string, two: string, three: boolean): number;}\n```\n\nExample:\n```text\n/* OK */interface Example {  diff(one: string, two?: string, three?: boolean): number;}\n```\n\nExample:\n```text\nfunction fn(x: (a: string, b: number, c: number) => void) {}var x: Example;// When written with overloads, OK -- used first overload// When written with optionals, correctly an errorfn(x.diff);\n```\n\nExample:\n```text\nvar x: Example;// When written with overloads, incorrectly an error because of passing 'undefined' to 'string'// When written with optionals, correctly OKx.diff(\"something\", true ? undefined : \"hour\");\n```\n\nExample:\n```text\n/* WRONG */interface Moment {  utcOffset(): number;  utcOffset(b: number): Moment;  utcOffset(b: string): Moment;}\n```\n\nExample:\n```text\n/* OK */interface Moment {  utcOffset(): number;  utcOffset(b: number | string): Moment;}\n```\n\nExample:\n```text\nfunction fn(x: string): Moment;function fn(x: number): Moment;function fn(x: number | string) {  // When written with separate overloads, incorrectly an error  // When written with union types, correctly OK  return moment().utcOffset(x);}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.374Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":91,"estimatedTokens":679}}56{"id":"doc-typescript_documentation_modules_d_ts-69d52312","source":"documentation","title":"TypeScript: Documentation - Modules .d.ts","url":"https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html","text":"Example:\n```text\nconst maxInterval = 12;function getArrayLength(arr) {  return arr.length;}module.exports = {  getArrayLength,  maxInterval,};\n```\n\nExample:\n```text\nexport function getArrayLength(arr: any[]): number;export const maxInterval: 12;\n```\n\nExample:\n```text\nexport function getArrayLength(arr) {  return arr.length;}\n```\n\nExample:\n```text\nexport function getArrayLength(arr: any[]): number;\n```\n\nExample:\n```text\nmodule.exports = /hello( world)?/;\n```\n\nExample:\n```text\ndeclare const helloWorld: RegExp;export = helloWorld;\n```\n\nExample:\n```text\nmodule.exports = 3.142;\n```\n\nExample:\n```text\ndeclare const pi: number;export = pi;\n```\n\nExample:\n```text\nfunction getArrayLength(arr) {  return arr.length;}getArrayLength.maxInterval = 12;module.exports = getArrayLength;\n```\n\nExample:\n```text\ndeclare function getArrayLength(arr: any[]): number;declare namespace getArrayLength {  declare const maxInterval: 12;}export = getArrayLength;\n```\n\nExample:\n```text\nconst 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\";\n```\n\nExample:\n```text\nclass FastifyInstance {}function fastify() {  return new FastifyInstance();}fastify.FastifyInstance = FastifyInstance;// Allows for { fastify }fastify.fastify = fastify;// Allows for strict ES Module supportfastify.default = fastify;// Sets the default exportmodule.exports = fastify;\n```\n\nExample:\n```text\nfunction getArrayMetadata(arr) {  return {    length: getArrayLength(arr),    firstObject: arr[0],  };}module.exports = {  getArrayMetadata,};\n```\n\nExample:\n```text\nexport type ArrayMetadata = {  length: number;  firstObject: any | undefined;};export function getArrayMetadata(arr: any[]): ArrayMetadata;\n```\n\nExample:\n```text\nexport type ArrayMetadata<ArrType> = {  length: number;  firstObject: ArrType | undefined;};export function getArrayMetadata<ArrType>(  arr: ArrType[]): ArrayMetadata<ArrType>;\n```\n\nExample:\n```text\n// This represents the JavaScript class which would be available at runtimeexport class API {  constructor(baseURL: string);  getInfo(opts: API.InfoRequest): API.InfoResponse;}// This namespace is merged with the API class and allows for consumers, and this file// to have types which are nested away in their own sections.declare namespace API {  export interface InfoRequest {    id: string;  }  export interface InfoResponse {    width: number;    height: number;  }}\n```\n\nExample:\n```text\nexport as namespace moduleName;\n```\n\nExample:\n```text\n// 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. 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' *//*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. *~ Otherwise, delete this declaration. */export as namespace myLib;/*~ If this module exports functions, declare them like so. */export function myFunction(a: string): string;export function myOtherFunction(a: number): number;/*~ You can declare types that are available via importing the module */export interface SomeType {  name: string;  length: number;  extras?: string[];}/*~ You can declare properties of the module using const, let, or var */export const myField: number;\n```\n\nExample:\n```text\nmyLib  +---- index.js  +---- foo.js  +---- bar         +---- index.js         +---- baz.js\n```\n\nExample:\n```text\nvar a = require(\"myLib\");var b = require(\"myLib/foo\");var c = require(\"myLib/bar\");var d = require(\"myLib/bar/baz\");\n```\n\nExample:\n```text\n@types/myLib  +---- index.d.ts  +---- foo.d.ts  +---- bar         +---- index.d.ts         +---- baz.d.ts\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.375Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":106,"estimatedTokens":1021}}57{"id":"doc-typescript_documentation_nightly_builds-57366a82","source":"documentation","title":"TypeScript: Documentation - Nightly Builds","url":"https://www.typescriptlang.org/docs/handbook/nightly-builds.html","text":"Example:\n```text\nnpm install -D typescript@next\n```\n\nExample:\n```text\n\"typescript.tsdk\": \"<path to your folder>/node_modules/typescript/lib\"\n```\n\nExample:\n```text\n\"typescript_tsdk\": \"<path to your folder>/node_modules/typescript/lib\"\n```\n\nExample:\n```text\nVSDevMode.ps1 14 -tsScript <path to your folder>/node_modules/typescript/lib\n```\n\nExample:\n```text\nVSDevMode.ps1 12 -tsScript <path to your folder>/node_modules/typescript/lib\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.375Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":26,"estimatedTokens":113}}58{"id":"doc-typescript_documentation_modules_reference-5d5a3506","source":"documentation","title":"TypeScript: Documentation - Modules - Reference","url":"https://www.typescriptlang.org/docs/handbook/modules/reference.html","text":"Example:\n```text\n// Standard JavaScript syntax...export function f() {}// ...extended to type declarationsexport type SomeType = /* ... */;export interface SomeInterface { /* ... */ }\n```\n\nExample:\n```text\nexport { f, SomeType, SomeInterface };\n```\n\nExample:\n```text\nimport { f, SomeType, SomeInterface } from \"./module.js\";\n```\n\nExample:\n```text\nimport * as mod from \"./module.js\";mod.f();mod.SomeType; // Property 'SomeType' does not exist on type 'typeof import(\"./module.js\")'let x: mod.SomeType; // Ok\n```\n\nExample:\n```text\n// @Filename: main.tsimport { f, type SomeInterface } from \"./module.js\";import type { SomeType } from \"./module.js\";class C implements SomeInterface {  constructor(p: SomeType) {    f();  }}export type { C };// @Filename: main.jsimport { f } from \"./module.js\";class C {  constructor(p) {    f();  }}\n```\n\nExample:\n```text\nimport type { f } from \"./module.js\";f(); // 'f' cannot be used as a value because it was imported using 'import type'let otherFunction: typeof f = () => {}; // Ok\n```\n\nExample:\n```text\nimport type fs, { BigIntOptions } from \"fs\";//          ^^^^^^^^^^^^^^^^^^^^^// Error: A type-only import can specify a default import or named bindings, but not both.import type { default as fs, BigIntOptions } from \"fs\"; // Ok\n```\n\nExample:\n```text\n// Access an exported type:type WriteFileOptions = import(\"fs\").WriteFileOptions;// Access the type of an exported value:type WriteFileFunction = typeof import(\"fs\").writeFile;\n```\n\nExample:\n```text\n/** @type {import(\"webpack\").Configuration} */module.exports = {  // ...}\n```\n\nExample:\n```text\n// @Filename: main.tsimport fs = require(\"fs\");export = fs.readFileSync(\"...\");// @Filename: main.js\"use strict\";const fs = require(\"fs\");module.exports = fs.readFileSync(\"...\");\n```\n\nExample:\n```text\n// @Filename: a.tsinterface Options { /* ... */ }module.exports = Options; // Error: 'Options' only refers to a type, but is being used as a value here.export = Options; // Ok// @Filename: b.tsconst Options = require(\"./a\");const options: Options = { /* ... */ }; // Error: 'Options' refers to a value, but is being used as a type here.// @Filename: c.tsimport Options = require(\"./a\");const options: Options = { /* ... */ }; // Ok\n```\n\nExample:\n```text\ndeclare module \"path\" {  export function normalize(p: string): string;  export function join(...paths: any[]): string;  export var sep: string;}\n```\n\nExample:\n```text\n// 👇 Ensure the ambient module is loaded -//    may be unnecessary if path.d.ts is included//    by the project tsconfig.json somehow./// <reference path=\"path.d.ts\" />import { normalize, join } from \"path\";\n```\n\nExample:\n```text\n// Not an ambient module declaration anymore!export {};declare module \"path\" {  export function normalize(p: string): string;  export function join(...paths: any[]): string;  export var sep: string;}\n```\n\nExample:\n```text\ndeclare module \"m\" {  // Moving this outside \"m\" would totally change the meaning of the file!  import { SomeType } from \"other\";  export function f(): SomeType;}\n```\n\nExample:\n```text\ndeclare module \"*.html\" {  const content: string;  export default content;}\n```\n\nExample:\n```text\n// @Filename: main.tsimport x = require(\"mod\");\n```\n\nExample:\n```text\n// @Filename: main.jsimport { createRequire as _createRequire } from \"module\";const __require = _createRequire(import.meta.url);const x = __require(\"mod\");\n```\n\nExample:\n```text\n// @Filename: main.tsimport fs from \"fs\"; // transformedconst dynamic = import(\"mod\"); // not transformed\n```\n\nExample:\n```text\n// @Filename: main.js\"use strict\";var __importDefault = (this && this.__importDefault) || function (mod) {    return (mod && mod.__esModule) ? mod : { \"default\": mod };};Object.defineProperty(exports, \"__esModule\", { value: true });const fs_1 = __importDefault(require(\"fs\")); // transformedconst dynamic = import(\"mod\"); // not transformed\n```\n\nExample:\n```text\n// @Filename: main.tsimport x, { y, z } from \"mod\";import mod = require(\"mod\");const dynamic = import(\"mod\");export const e1 = 0;export default \"default export\";\n```\n\nExample:\n```text\n// @Filename: main.jsimport x, { y, z } from \"mod\";const mod = require(\"mod\");const dynamic = import(\"mod\");export const e1 = 0;export default \"default export\";\n```\n\nExample:\n```text\n// @Filename: main.tsimport 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\";\n```\n\nExample:\n```text\n// @Filename: main.jsimport 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\";\n```\n\nExample:\n```text\n// @Filename: main.js\"use strict\";Object.defineProperty(exports, \"__esModule\", { value: true });exports.e1 = void 0;const mod_1 = require(\"mod\");const mod = require(\"mod\");const dynamic = Promise.resolve().then(() => require(\"mod\"));console.log(mod_1.default, mod_1.y, mod_1.z, mod);exports.e1 = 0;exports.default = \"default export\";\n```\n\nExample:\n```text\n// @Filename: main.tsimport mod = require(\"mod\");console.log(mod);export = {    p1: true,    p2: false};\n```\n\nExample:\n```text\n// @Filename: main.js\"use strict\";const mod = require(\"mod\");console.log(mod);module.exports = {    p1: true,    p2: false};\n```\n\nExample:\n```text\n// @Filename: main.jsSystem.register([\"mod\"], function (exports_1, context_1) {    \"use strict\";    var mod_1, mod, dynamic, e1;    var __moduleName = context_1 && context_1.id;    return {        setters: [            function (mod_1_1) {                mod_1 = mod_1_1;                mod = mod_1_1;            }        ],        execute: function () {            dynamic = context_1.import(\"mod\");            console.log(mod_1.default, mod_1.y, mod_1.z, mod, dynamic);            exports_1(\"e1\", e1 = 0);            exports_1(\"default\", \"default export\");        }    };});\n```\n\nExample:\n```text\n// @Filename: main.jsdefine([\"require\", \"exports\", \"mod\", \"mod\"], function (require, exports, mod_1, mod) {    \"use strict\";    Object.defineProperty(exports, \"__esModule\", { value: true });    exports.e1 = void 0;    const dynamic = new Promise((resolve_1, reject_1) => { require([\"mod\"], resolve_1, reject_1); });    console.log(mod_1.default, mod_1.y, mod_1.z, mod, dynamic);    exports.e1 = 0;    exports.default = \"default export\";});\n```\n\nExample:\n```text\n// @Filename: main.js(function (factory) {    if (typeof module === \"object\" && typeof module.exports === \"object\") {        var v = factory(require, exports);        if (v !== undefined) module.exports = v;    }    else if (typeof define === \"function\" && define.amd) {        define([\"require\", \"exports\", \"mod\", \"mod\"], factory);    }})(function (require, exports) {    \"use strict\";    var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";    Object.defineProperty(exports, \"__esModule\", { value: true });    exports.e1 = void 0;    const mod_1 = require(\"mod\");    const mod = require(\"mod\");    const dynamic = __syncRequire ? Promise.resolve().then(() => require(\"mod\")) : new Promise((resolve_1, reject_1) => { require([\"mod\"], resolve_1, reject_1); });    console.log(mod_1.default, mod_1.y, mod_1.z, mod, dynamic);    exports.e1 = 0;    exports.default = \"default export\";});\n```\n\nExample:\n```text\nimport x from \"./mod.js\";// Runtime lookup: \"./mod.js\"// TypeScript lookup #1: \"./mod.ts\"// TypeScript lookup #2: \"./mod.d.ts\"// TypeScript lookup #3: \"./mod.js\"\n```\n\nExample:\n```text\n// @Filename: a.tsexport {};// @Filename: b.tsimport {} from \"./a.js\"; // ✅ Works in every `moduleResolution`\n```\n\nExample:\n```text\n// @Filename: a.tsexport {};// @Filename: b.tsimport {} from \"./a\";\n```\n\nExample:\n```text\n// @Filename: dir/index.tsexport {};// @Filename: b.tsimport {} from \"./dir\";\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"module\": \"nodenext\",    \"paths\": {      \"https://esm.sh/lodash@4.17.21\": [\"./node_modules/@types/lodash/index.d.ts\"]    }  }}\n```\n\nExample:\n```text\n// Typed by ./node_modules/@types/lodash/index.d.ts due to `paths` entryimport { add } from \"https://esm.sh/lodash@4.17.21\";\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"module\": \"esnext\",    \"moduleResolution\": \"bundler\",    \"paths\": {      \"@app/*\": [\"./src/*\"]    }  }}\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"module\": \"nodenext\",    \"paths\": {      \"node-has-no-idea-what-this-is\": [\"./oops.ts\"]    }  }}\n```\n\nExample:\n```text\n// TypeScript: ✅// Node.js: 💥import {} from \"node-has-no-idea-what-this-is\";\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"paths\": {      \"pkg\": [\"./node_modules/pkg/dist/index.d.ts\"],      \"pkg/*\": [\"./node_modules/pkg/*\"]    }  }}\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"paths\": {      \"@app/*\": [\"./src/*\"]    }  }}\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"paths\": {      \"*\": [\"./src/foo/one.ts\"],      \"foo/*\": [\"./src/foo/two.ts\"],      \"foo/bar\": [\"./src/foo/three.ts\"]    }  }}\n```\n\nExample:\n```text\n{  \"compilerOptions\": {    \"paths\": {      \"*\": [\"./vendor/*\", \"./types/*\"]    }  }}\n```\n\nExample:\n```text\n{  \"name\": \"pkg\",  \"exports\": {    \".\": {      \"import\": \"./index.mjs\",      \"require\": \"./index.cjs\"    },    \"./subpath\": {      \"import\": \"./subpath/index.mjs\",      \"require\": \"./subpath/index.cjs\"    }  }}\n```\n\nExample:\n```text\n{  \"name\": \"pkg\",  \"exports\": {    \"./subpath\": {      \"import\": {        \"types\": \"./types/subpath/index.d.mts\",        \"default\": \"./es/subpath/index.mjs\"      },      \"require\": {        \"types\": \"./types/subpath/index.d.cts\",        \"default\": \"./cjs/subpath/index.cjs\"      }    }  }}\n```\n\nExample:\n```text\n{  \"name\": \"pkg\",  \"exports\": {    \"./subpath\": {      \"types@>=5.2\": \"./ts5.2/subpath/index.d.ts\",      \"types@>=4.6\": \"./ts4.6/subpath/index.d.ts\",      \"types\": \"./tsold/subpath/index.d.ts\",      \"default\": \"./dist/subpath/index.js\"    }  }}\n```\n\nExample:\n```text\n{  \"name\": \"pkg\",  \"type\": \"module\",  \"exports\": {    \"./*.js\": {      \"types\": \"./types/*.d.ts\",      \"default\": \"./dist/*.js\"    }  }}\n```\n\nExample:\n```text\n{  \"name\": \"pkg\",  \"main\": \"./dist/index.js\",  \"exports\": \"./dist/index.js\"}\n```\n\nExample:\n```text\n{  \"name\": \"pkg\",  \"version\": \"1.0.0\",  \"types\": \"./index.d.ts\",  \"typesVersions\": {    \">=3.1\": {      \"*\": [\"ts3.1/*\"]    }  }}\n```\n\nExample:\n```text\n{  \"name\": \"pkg\",  \"version\": \"1.0.0\",  \"types\": \"./index.d.ts\",  \"typesVersions\": {    \"<4.0\": { \"index.d.ts\": [\"index.v3.d.ts\"] }  }}\n```\n\nExample:\n```text\n// @Filename: module.mtsimport \"pkg/dist/foo\";                // ❌ import, needs `.js` extensionimport \"pkg/dist/foo.js\";             // ✅import foo = require(\"pkg/dist/foo\"); // ✅ require, no extension needed\n```\n\nExample:\n```text\n// tsconfig.json{  \"compilerOptions\": {    \"moduleResolution\": \"node16\",    \"resolvePackageJsonImports\": true,    \"rootDir\": \"./src\",    \"outDir\": \"./dist\"  }}\n```\n\nExample:\n```text\n// package.json{  \"name\": \"pkg\",  \"imports\": {    \"#utils\": {      \"import\": \"./dist/utils.d.mts\",      \"require\": \"./dist/utils.d.cts\"    }  }}\n```\n\nExample:\n```text\n// /node_modules/pkg/package.json{  \"name\": \"pkg\",  \"imports\": {    \"#internal/*\": {      \"import\": \"./dist/internal/*.mjs\",      \"require\": \"./dist/internal/*.cjs\"    }  }}\n```\n\nExample:\n```text\n// @Filename: module.mtsimport 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 formatimport mod = require(\"./mod\");        // `require` algorithm due to syntax (emitted as `require`)// @Filename: commonjs.ctsimport 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 formatimport mod = require(\"./mod\");        // `require` algorithm due to syntax (emitted as `require`)\n```\n\nExample:\n```text\n// index.tsimport { foo } from \"pkg\";\n```\n\nExample:\n```text\n// index.tsimport pkg1 from \"pkg\";       // Resolved with \"import\" conditionimport pkg2 = require(\"pkg\"); // Resolved with \"require\" condition\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.377Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":57,"totalLines":286,"estimatedTokens":3069}}59{"id":"doc-typescript_documentation_type_checking_javascrip-8c00e42e","source":"documentation","title":"TypeScript: Documentation - Type Checking JavaScript Files","url":"https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html","text":"Example:\n```text\nclass C {  constructor() {    this.constructorOnly = 0;    this.constructorUnknown = undefined;  }  method() {    this.constructorOnly = false;Type 'boolean' is not assignable to type 'number'.2322Type 'boolean' is not assignable to type 'number'.    this.constructorUnknown = \"plunkbat\"; // ok, constructorUnknown is string | undefined    this.methodOnly = \"ok\"; // ok, but methodOnly could also be undefined  }  method2() {    this.methodOnly = true; // also, ok, methodOnly's type is string | boolean | undefined  }}\n```\n\nExample:\n```text\nclass C {  constructor() {    /** @type {number | undefined} */    this.prop = undefined;    /** @type {number | undefined} */    this.count;  }} let c = new C();c.prop = 0; // OKc.count = \"string\";Type 'string' is not assignable to type 'number'.2322Type 'string' is not assignable to type 'number'.\n```\n\nExample:\n```text\nfunction C() {  this.constructorOnly = 0;  this.constructorUnknown = undefined;}C.prototype.method = function () {  this.constructorOnly = false;Type 'boolean' is not assignable to type 'number'.2322Type 'boolean' is not assignable to type 'number'.  this.constructorUnknown = \"plunkbat\"; // OK, the type is string | undefined};\n```\n\nExample:\n```text\n// same as `import module \"fs\"`const fs = require(\"fs\");// same as `export function readFile`module.exports.readFile = function (f) {  return fs.readFileSync(f);};\n```\n\nExample:\n```text\nclass C {}C.D = class {};\n```\n\nExample:\n```text\nfunction Outer() {  this.y = 2;} Outer.Inner = function () {  this.yy = 2;}; Outer.Inner();\n```\n\nExample:\n```text\nvar ns = {};ns.C = class {};ns.func = function () {}; ns;\n```\n\nExample:\n```text\n// IIFEvar ns = (function (n) {  return n || {};})();ns.CONST = 1; // defaulting to globalvar assign =  assign ||  function () {    // code goes here  };assign.extra = 1;\n```\n\nExample:\n```text\nvar obj = { a: 1 };obj.b = 2; // Allowed\n```\n\nExample:\n```text\n/** @type {{a: number}} */var obj = { a: 1 };obj.b = 2;Property 'b' does not exist on type '{ a: number; }'.2339Property 'b' does not exist on type '{ a: number; }'.\n```\n\nExample:\n```text\nfunction Foo(i = null) {  if (!i) i = 1;  var j = undefined;  j = 2;  this.l = [];} var foo = new Foo();foo.l.push(foo.i);foo.l.push(\"end\");\n```\n\nExample:\n```text\nfunction bar(a, b) {  console.log(a + \" \" + b);} bar(1); // OK, second argument considered optionalbar(1, 2);bar(1, 2, 3); // Error, too many argumentsExpected 0-2 arguments, but got 3.2554Expected 0-2 arguments, but got 3.\n```\n\nExample:\n```text\n/** * @param {string} [somebody] - Somebody's name. */function sayHello(somebody) {  if (!somebody) {    somebody = \"John Doe\";  }  console.log(\"Hello \" + somebody);} sayHello();\n```\n\nExample:\n```text\n/** @param {...number} args */function sum(/* numbers */) {  var total = 0;  for (var i = 0; i < arguments.length; i++) {    total += arguments[i];  }  return total;}\n```\n\nExample:\n```text\nimport { Component } from \"react\";class MyComponent extends Component {  render() {    this.props.b; // Allowed, since this.props is of type any  }}\n```\n\nExample:\n```text\nimport { Component } from \"react\";/** * @augments {Component<{a: number}, State>} */class MyComponent extends Component {  render() {    this.props.b; // Error: b does not exist on {a:number}  }}\n```\n\nExample:\n```text\n/** @type{Array} */var x = []; x.push(1); // OKx.push(\"string\"); // OK, x is of type Array<any> /** @type{Array.<number>} */var y = []; y.push(1); // OKy.push(\"string\"); // Error, string is not assignable to number\n```\n\nExample:\n```text\nvar p = new Promise((resolve, reject) => {  reject();});p; // Promise<any>;\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.378Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":91,"estimatedTokens":906}}60{"id":"doc-typescript_documentation_compiler_options_in_msb-0294ff94","source":"documentation","title":"TypeScript: Documentation - Compiler Options in MSBuild","url":"https://www.typescriptlang.org/docs/handbook/compiler-options-in-msbuild.html","text":"Example:\n```text\n<PropertyGroup>  <TypeScriptNoEmitOnError>true</TypeScriptNoEmitOnError>  <TypeScriptNoImplicitReturns>true</TypeScriptNoImplicitReturns></PropertyGroup>\n```\n\nExample:\n```text\n<TypeScriptAdditionalFlags> $(TypeScriptAdditionalFlags) --noPropertyAccessFromIndexSignature</TypeScriptAdditionalFlags>\n```\n\nExample:\n```text\n<PropertyGroup Condition=\"'$(Configuration)' == 'Debug'\">  <TypeScriptRemoveComments>false</TypeScriptRemoveComments>  <TypeScriptSourceMap>true</TypeScriptSourceMap></PropertyGroup><PropertyGroup Condition=\"'$(Configuration)' == 'Release'\">  <TypeScriptRemoveComments>true</TypeScriptRemoveComments>  <TypeScriptSourceMap>false</TypeScriptSourceMap></PropertyGroup><Import    Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\TypeScript\\Microsoft.TypeScript.targets\"    Condition=\"Exists('$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\TypeScript\\Microsoft.TypeScript.targets')\" />\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.378Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":16,"estimatedTokens":250}}61{"id":"doc-typescript_documentation_integrating_with_build_-7992e46f","source":"documentation","title":"TypeScript: Documentation - Integrating with Build Tools","url":"https://www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html","text":"Example:\n```text\nnpm install @babel/cli @babel/core @babel/preset-typescript --save-dev\n```\n\nExample:\n```text\n{  \"presets\": [\"@babel/preset-typescript\"]}\n```\n\nExample:\n```text\n./node_modules/.bin/babel --out-file bundle.js src/index.ts\n```\n\nExample:\n```text\n{  \"scripts\": {    \"build\": \"babel --out-file bundle.js main.ts\"  },}\n```\n\nExample:\n```text\nnpm run build\n```\n\nExample:\n```text\nnpm install tsify\n```\n\nExample:\n```text\nbrowserify main.ts -p [ tsify --noImplicitAny ] > bundle.js\n```\n\nExample:\n```text\nvar browserify = require(\"browserify\");var tsify = require(\"tsify\");browserify()  .add(\"main.ts\")  .plugin(\"tsify\", { noImplicitAny: true })  .bundle()  .pipe(process.stdout);\n```\n\nExample:\n```text\nnpm install grunt-ts --save-dev\n```\n\nExample:\n```text\nmodule.exports = function (grunt) {  grunt.initConfig({    ts: {      default: {        src: [\"**/*.ts\", \"!node_modules/**/*.ts\"],      },    },  });  grunt.loadNpmTasks(\"grunt-ts\");  grunt.registerTask(\"default\", [\"ts\"]);};\n```\n\nExample:\n```text\nnpm install grunt-browserify tsify --save-dev\n```\n\nExample:\n```text\nmodule.exports = function (grunt) {  grunt.initConfig({    browserify: {      all: {        src: \"src/main.ts\",        dest: \"dist/main.js\",        options: {          plugin: [\"tsify\"],        },      },    },  });  grunt.loadNpmTasks(\"grunt-browserify\");  grunt.registerTask(\"default\", [\"browserify\"]);};\n```\n\nExample:\n```text\nnpm install gulp-typescript\n```\n\nExample:\n```text\nvar gulp = require(\"gulp\");var ts = require(\"gulp-typescript\");gulp.task(\"default\", function () {  var tsResult = gulp.src(\"src/*.ts\").pipe(    ts({      noImplicitAny: true,      out: \"output.js\",    })  );  return tsResult.js.pipe(gulp.dest(\"built/local\"));});\n```\n\nExample:\n```text\nnpm install -g jspm@beta\n```\n\nExample:\n```text\n<?xml version=\"1.0\" encoding=\"utf-8\"?><Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">  <!-- Include default props at the top -->  <Import      Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\TypeScript\\Microsoft.TypeScript.Default.props\"      Condition=\"Exists('$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\TypeScript\\Microsoft.TypeScript.Default.props')\" />  <!-- TypeScript configurations go here -->  <PropertyGroup Condition=\"'$(Configuration)' == 'Debug'\">    <TypeScriptRemoveComments>false</TypeScriptRemoveComments>    <TypeScriptSourceMap>true</TypeScriptSourceMap>  </PropertyGroup>  <PropertyGroup Condition=\"'$(Configuration)' == 'Release'\">    <TypeScriptRemoveComments>true</TypeScriptRemoveComments>    <TypeScriptSourceMap>false</TypeScriptSourceMap>  </PropertyGroup>  <!-- Include default targets at the bottom -->  <Import      Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\TypeScript\\Microsoft.TypeScript.targets\"      Condition=\"Exists('$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\\TypeScript\\Microsoft.TypeScript.targets')\" /></Project>\n```\n\nExample:\n```text\nnpm install @rollup/plugin-typescript --save-dev\n```\n\nExample:\n```text\n// rollup.config.jsimport typescript from '@rollup/plugin-typescript';export default {  input: 'src/index.ts',  output: {    dir: 'output',    format: 'cjs'  },  plugins: [typescript()]};\n```\n\nExample:\n```text\nnpm install --save-dev svelte-preprocess\n```\n\nExample:\n```text\n// svelte.config.jsimport preprocess from 'svelte-preprocess';const config = {  // Consult https://github.com/sveltejs/svelte-preprocess  // for more information about preprocessors  preprocess: preprocess()};export default config;\n```\n\nExample:\n```text\n<script lang=\"ts\">\n```\n\nExample:\n```text\nnpm install ts-loader --save-dev\n```\n\nExample:\n```text\nconst path = require('path');module.exports = {  entry: './src/index.ts',  module: {    rules: [      {        test: /\\.tsx?$/,        use: 'ts-loader',        exclude: /node_modules/,      },    ],  },  resolve: {    extensions: ['.tsx', '.ts', '.js'],  },  output: {    filename: 'bundle.js',    path: path.resolve(__dirname, 'dist'),  },};\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.379Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":116,"estimatedTokens":1029}}62{"id":"doc-typescript_documentation_configuring_watch-f448d285","source":"documentation","title":"TypeScript: Documentation - Configuring Watch","url":"https://www.typescriptlang.org/docs/handbook/configuring-watch.html","text":"Example:\n```typescript\n{  // Some typical compiler options  \"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\",    // Don't coalesce watch notification    \"synchronousWatchDirectory\": true,    // Finally, two additional settings for reducing the amount of possible    // files to track  work from these directories    \"excludeDirectories\": [\"**/node_modules\", \"_build\"],    \"excludeFiles\": [\"build/fileWhichChangesOften.ts\"]  }}\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.379Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":6,"estimatedTokens":199}}63{"id":"doc-typescript_documentation_project_references-f31d37d8","source":"documentation","title":"TypeScript: Documentation - Project References","url":"https://www.typescriptlang.org/docs/handbook/project-references.html","text":"Example:\n```text\n/├── src/│   ├── converter.ts│   └── units.ts├── test/│   ├── converter-tests.ts│   └── units-tests.ts└── tsconfig.json\n```\n\nExample:\n```text\n// converter-tests.tsimport * as converter from \"../src/converter\";assert.areEqual(converter.celsiusToFahrenheit(0), 32);\n```\n\nExample:\n```text\n{    \"compilerOptions\": {        // The usual    },    \"references\": [        { \"path\": \"../src\" }    ]}\n```\n\nExample:\n```text\n> tsc -b                            # Use the tsconfig.json in the current directory > tsc -b src                        # Use src/tsconfig.json > tsc -b foo/prd.tsconfig.json bar  # Use foo/prd.tsconfig.json and bar/tsconfig.json\n```\n\nExample:\n```text\n<TypeScriptBuildMode>true</TypeScriptBuildMode>\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.379Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":26,"estimatedTokens":187}}64{"id":"doc-typescript_documentation_tsc_cli_options-df2cdbce","source":"documentation","title":"TypeScript: Documentation - tsc CLI Options","url":"https://www.typescriptlang.org/docs/handbook/compiler-options.html","text":"Example:\n```text\n# Run a compile based on a backwards look through the fs for a tsconfig.jsontsc# Emit JS for just the index.ts with the compiler defaultstsc index.ts# Emit JS for any .ts files in the folder src, with the default settingstsc src/*.ts# Emit files referenced in with the compiler settings from tsconfig.production.jsontsc --project tsconfig.production.json# Emit d.ts files for a js file with showing compiler options which are booleanstsc index.js --declaration --emitDeclarationOnly# Emit a single .js file from two files via compiler options which take string argumentstsc app.ts util.ts --target esnext --outfile index.js\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.380Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":6,"estimatedTokens":165}}65{"id":"doc-typescript_documentation_jsdoc_reference-e0d8c72f","source":"documentation","title":"TypeScript: Documentation - JSDoc Reference","url":"https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html","text":"Example:\n```text\n/** * @type {string} */var s; /** @type {Window} */var win; /** @type {PromiseLike<string>} */var promisedString; // You can specify an HTML Element with DOM properties/** @type {HTMLElement} */var myElement = document.querySelector(selector);element.dataset.myData = \"\";\n```\n\nExample:\n```text\n/** * @type {string | boolean} */var sb;\n```\n\nExample:\n```text\n/** @type {number[]} */var ns;/** @type {Array.<number>} */var jsdoc;/** @type {Array<number>} */var nas;\n```\n\nExample:\n```text\n/** @type {{ a: string, b: number }} */var var9;\n```\n\nExample:\n```text\n/** * A map-like object that maps arbitrary `string` properties to `number`s. * * @type {Object.<string, number>} */var stringToNumber; /** @type {Object.<number, object>} */var arrayLike;\n```\n\nExample:\n```text\n/** @type {function(string, boolean): number} Closure syntax */var sbn;/** @type {(s: string, b: boolean) => number} TypeScript syntax */var sbn2;\n```\n\nExample:\n```text\n/** @type {Function} */var fn7;/** @type {function} */var fn6;\n```\n\nExample:\n```text\n/** * @type {*} - can be 'any' type */var star;/** * @type {?} - unknown type (same as 'any') */var question;\n```\n\nExample:\n```text\n/** * @type {number | string} */var numberOrString = Math.random() < 0.5 ? \"hello\" : 100;var typeAssertedNumber = /** @type {number} */ (numberOrString);\n```\n\nExample:\n```text\nlet one = /** @type {const} */(1);\n```\n\nExample:\n```text\n// @filename: types.d.tsexport type Pet = {  name: string,}; // @filename: main.js/** * @param {import(\"./types\").Pet} p */function walk(p) {  console.log(`Walking ${p.name}...`);}\n```\n\nExample:\n```text\n/** * @type {typeof import(\"./accounts\").userAccount} */var x = require(\"./accounts\").userAccount;\n```\n\nExample:\n```text\n/** * @import {Pet} from \"./types\" */ /** * @type {Pet} */var myPet;myPet.name;\n```\n\nExample:\n```text\n// @filename: dog.jsexport class Dog {  woof() {    console.log(\"Woof!\");  }} // @filename: main.js/** @import { Dog } from \"./dog.js\" */ const d = new Dog(); // error!\n```\n\nExample:\n```text\n// Parameters may be declared in a variety of syntactic forms/** * @param {string}  p1 - A string param. * @param {string=} p2 - An optional param (Google Closure syntax) * @param {string} [p3] - Another optional param (JSDoc syntax). * @param {string} [p4=\"test\"] - An optional param with a default value * @returns {string} This is the result */function stringsStringStrings(p1, p2, p3, p4) {  // TODO}\n```\n\nExample:\n```text\n/** * @return {PromiseLike<string>} */function ps() {} /** * @returns {{ a: string, b: number }} - May use '@returns' as well as '@return' */function ab() {}\n```\n\nExample:\n```text\n/** * @typedef {Object} SpecialType - creates a new type named 'SpecialType' * @property {string} prop1 - a string property of SpecialType * @property {number} prop2 - a number property of SpecialType * @property {number=} prop3 - an optional number property of SpecialType * @prop {number} [prop4] - an optional number property of SpecialType * @prop {number} [prop5=42] - an optional number property of SpecialType with default */ /** @type {SpecialType} */var specialTypeObject;specialTypeObject.prop3;\n```\n\nExample:\n```text\n/** * @typedef {object} SpecialType1 - creates a new type named 'SpecialType1' * @property {string} prop1 - a string property of SpecialType1 * @property {number} prop2 - a number property of SpecialType1 * @property {number=} prop3 - an optional number property of SpecialType1 */ /** @type {SpecialType1} */var specialTypeObject1;\n```\n\nExample:\n```text\n/** * @param {Object} options - The shape is the same as SpecialType above * @param {string} options.prop1 * @param {number} options.prop2 * @param {number=} options.prop3 * @param {number} [options.prop4] * @param {number} [options.prop5=42] */function special(options) {  return (options.prop4 || 1001) + options.prop5;}\n```\n\nExample:\n```text\n/** * @callback Predicate * @param {string} data * @param {number} [index] * @returns {boolean} */ /** @type {Predicate} */const ok = (s) => !(s.length % 2);\n```\n\nExample:\n```text\n/** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType *//** @typedef {(data: string, index?: number) => boolean} Predicate */\n```\n\nExample:\n```text\n/** * @template T * @param {T} x - A generic parameter that flows through to the return type * @returns {T} */function id(x) {  return x;} const a = id(\"string\");const b = id(123);const c = id({});\n```\n\nExample:\n```text\n/** * @template T,U,V * @template W,X */\n```\n\nExample:\n```text\n/** * @template {string} K - K must be a string or string literal * @template {{ serious(): string }} Seriousalizable - must have a serious method * @param {K} key * @param {Seriousalizable} object */function seriousalize(key, object) {  // ????}\n```\n\nExample:\n```text\n/** @template [T=object] */class Cache {    /** @param {T} initial */    constructor(initial) {    }}let c = new Cache()\n```\n\nExample:\n```text\n// @ts-check/** * @typedef {\"hello world\" | \"Hello, world\"} WelcomeMessage */ /** @satisfies {WelcomeMessage} */const message = \"hello world\"        const message: \"hello world\" /** @satisfies {WelcomeMessage} */Type '\"Hello world!\"' does not satisfy the expected type 'WelcomeMessage'.1360Type '\"Hello world!\"' does not satisfy the expected type 'WelcomeMessage'.const failingMessage = \"Hello world!\" /** @type {WelcomeMessage} */const messageUsingType = \"hello world\"             const messageUsingType: WelcomeMessage\n```\n\nExample:\n```text\nclass C {  /**   * @param {number} data   */  constructor(data) {    // property types can be inferred    this.name = \"foo\";     // or set explicitly    /** @type {string | null} */    this.title = null;     // or simply annotated, if they're set elsewhere    /** @type {number} */    this.size;     this.initialize(data); // Should error, initializer expects a string  }  /**   * @param {string} s   */  initialize = function (s) {    this.size = s.length;  };} var c = new C(0); // C should only be called with new, but// because it is JavaScript, this is allowed and// considered an 'any'.var result = C(1);\n```\n\nExample:\n```text\n// @ts-check class Car {  constructor() {    /** @private */    this.identifier = 100;  }   printIdentifier() {    console.log(this.identifier);  }} const c = new Car();console.log(c.identifier);Property 'identifier' is private and only accessible within class 'Car'.2341Property 'identifier' is private and only accessible within class 'Car'.\n```\n\nExample:\n```text\n// @ts-check class Car {  constructor() {    /** @readonly */    this.identifier = 100;  }   printIdentifier() {    console.log(this.identifier);  }} const c = new Car();console.log(c.identifier);\n```\n\nExample:\n```text\nexport class C {  m() { }}class D extends C {  /** @override */  m() { }}\n```\n\nExample:\n```text\n/** * @template T * @extends {Set<T>} */class SortableSet extends Set {  // ...}\n```\n\nExample:\n```text\n/** @implements {Print} */class TextBook {  print() {    // TODO  }}\n```\n\nExample:\n```text\n/** * @constructor * @param {number} data */function C(data) {  // property types can be inferred  this.name = \"foo\";   // or set explicitly  /** @type {string | null} */  this.title = null;   // or simply annotated, if they're set elsewhere  /** @type {number} */  this.size;   this.initialize(data);Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.}/** * @param {string} s */C.prototype.initialize = function (s) {  this.size = s.length;}; var c = new C(0);c.size; var result = C(1);Value of type 'typeof C' is not callable. Did you mean to include 'new'?2348Value of type 'typeof C' is not callable. Did you mean to include 'new'?\n```\n\nExample:\n```text\n/** * @this {HTMLElement} * @param {*} e */function callbackForLater(e) {  this.clientHeight = parseInt(e); // should be fine!}\n```\n\nExample:\n```text\n/** @deprecated */const apiV1 = {};const apiV2 = {}; apiV;   apiV1apiV2\n```\n\nExample:\n```text\ntype Box<T> = { t: T }/** @see Box for implementation details */type Boxify<T> = { [K in keyof T]: Box<T> };\n```\n\nExample:\n```text\ntype Box<T> = { t: T }/** @returns A {@link Box} containing the parameter. */function box<U>(u: U): Box<U> {  return { t: u };}\n```\n\nExample:\n```text\ntype Pet = {  name: string  hello: () => string} /** * Note: you should implement the {@link Pet.hello} method of Pet. */function hello(p: Pet) {  p.hello()}\n```\n\nExample:\n```text\ntype Pet = {  name: string  hello: () => string} /** * Note: you should implement the {@link Pet.hello | hello} method of Pet. */function hello(p: Pet) {  p.hello()}\n```\n\nExample:\n```text\n/** @enum {number} */const JSDocState = {  BeginningOfLine: 0,  SawAsterisk: 1,  SavingComments: 2,}; JSDocState.SawAsterisk;\n```\n\nExample:\n```text\n/** @enum {function(number): number} */const MathFuncs = {  add1: (n) => n + 1,  id: (n) => -n,  sub1: (n) => n - 1,}; MathFuncs.add1;\n```\n\nExample:\n```text\n/** * Welcome to awesome.ts * @author Ian Awesome <i.am.awesome@example.com> */\n```\n\nExample:\n```text\nvar someObj = {  /**   * @param {string} param1 - JSDocs on property assignments work   */  x: function (param1) {},}; /** * As do jsdocs on variable assignments * @return {Window} */let someFunc = function () {}; /** * And class methods * @param {string} greeting The greeting to use */Foo.prototype.sayHi = (greeting) => console.log(\"Hi!\"); /** * And arrow function expressions * @param {number} x - A multiplier */let myArrow = (x) => x * x; /** * Which means it works for function components in JSX too * @param {{a: string, b: number}} props - Some param */var fc = (props) => <div>{props.a.charAt(0)}</div>; /** * A parameter can be a class constructor, using Google Closure syntax. * * @param {{new(...args: any[]): object}} C - The class to register */function registerClass(C) {} /** * @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any') */function fn10(p1) {} /** * @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any') */function fn9(p1) {  return p1.join();}\n```\n\nExample:\n```text\n/** * @type {{ a: string, b: number= }} */var wrong;/** * Use postfix question on the property name instead: * @type {{ a: string, b?: number }} */var right;\n```\n\nExample:\n```text\n/** * @type {?number} * With strictNullChecks: true  -- number | null * With strictNullChecks: false -- number */var nullable;\n```\n\nExample:\n```text\n/** * @type {number | null} * With strictNullChecks: true  -- number | null * With strictNullChecks: false -- number */var unionNullable;\n```\n\nExample:\n```text\n/** * @type {!number} * Just has type number */var normal;\n```\n\n<|endofdoc|>","metadata":{"transformedAt":"2026-08-18T15:21:47.381Z","totalSectionsIncluded":0,"totalCodeBlocksIncluded":47,"totalLines":236,"estimatedTokens":2654}}66