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.ResolvedTypeReferenceDirectiveWithFailedLookupLocations

Parameters & Attributes

NameTypeDescription
typeReferenceDirectiveNamestringName of a type package or directive.
containingFilestring | undefinedContaining file path, or undefined.
optionsts.CompilerOptionsType resolution settings.
hostts.ModuleResolutionHostFile and directory lookup services.
redirectedReferencets.ResolvedProjectReferenceOptional project reference context.
cachets.TypeReferenceDirectiveResolutionCacheOptional compatible directive cache.
resolutionModets.ResolutionModeOptional 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
TypeScript Reference