TypeScript Compiler API
ts.resolveTypeReferenceDirective()
Resolves a type-reference directive name to a declaration entry using compiler options and host lookups. Inspect the optional resolvedTypeReferenceDirective field. This is not ordinary runtime import resolution and does not itself insert declarations into a Program. The fixture uses explicit typeRoots and a synthetic declaration package. Baseline: TypeScript 5.8.3 and Node.js. The example is a local tooling script in a disposable directory; it writes temporary project files, not a ByteMind CodeRunner exercise.
Formal Syntax & Structure
typescript syntaxtypescript
ts.resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: ts.CompilerOptions, host: ts.ModuleResolutionHost, redirectedReference?: ts.ResolvedProjectReference, cache?: ts.TypeReferenceDirectiveResolutionCache, resolutionMode?: ts.ResolutionMode): ts.ResolvedTypeReferenceDirectiveWithFailedLookupLocationsParameters & Attributes
| Name | Type | Description |
|---|---|---|
| typeReferenceDirectiveName | string | Name of a type package or directive. |
| containingFile | string | undefined | Containing file path, or undefined. |
| options | ts.CompilerOptions | Type resolution settings. |
| host | ts.ModuleResolutionHost | File and directory lookup services. |
| redirectedReference | ts.ResolvedProjectReference | Optional project reference context. |
| cache | ts.TypeReferenceDirectiveResolutionCache | Optional compatible directive cache. |
| resolutionMode | ts.ResolutionMode | Optional import/require resolution mode. |
Working Example
Example Snippettypescript
// Use a new empty directory. Install: npm install --save-exact typescript@5.8.3// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const fs = require("node:fs");const path = require("node:path");fs.mkdirSync("types/demo",{recursive:true}); fs.writeFileSync("types/demo/index.d.ts","declare const demo: number;");const main=path.resolve("main.ts"); fs.writeFileSync(main,"");const options={typeRoots:[path.resolve("types")],moduleResolution:ts.ModuleResolutionKind.Node10};const found=ts.resolveTypeReferenceDirective("demo",main,options,ts.sys).resolvedTypeReferenceDirective;assert(found); assert.equal(path.resolve(found.resolvedFileName),path.resolve("types/demo/index.d.ts"));assert.equal(ts.resolveTypeReferenceDirective("missing",main,options,ts.sys).resolvedTypeReferenceDirective,undefined);console.log("demo -> index.d.ts; missing -> unresolved");
// Run: node example.cjs// Expected stdout: demo -> index.d.ts; missing -> unresolved