11.1 Programs and Source Files

A TypeScript program consists of one or more source files.

  SourceFile:   ImplementationSourceFile   DeclarationSourceFile

  ImplementationSourceFile:   ImplementationScript   ImplementationModule

  DeclarationSourceFile:   DeclarationScript   DeclarationModule

Source files with extension ‘.ts’ are implementation source files containing statements and declarations, and source files with extension ‘.d.ts’ are declaration source files containing declarations only.

Declaration source files are a strict subset of implementation source files and are used to declare the static type information associated with existing JavaScript code in an adjunct manner. They are entirely optional but enable the TypeScript compiler and tools to provide better verification and assistance when integrating existing JavaScript code and libraries in a TypeScript application.

When a TypeScript program is compiled, all of the program’s source files are processed together. Statements and declarations in different source files can depend on each other, possibly in a circular fashion. By default, a JavaScript output file is generated for each implementation source file in a compilation, but no output is generated from declaration source files.

11.1.1 Source Files Dependencies

The TypeScript compiler automatically determines a source file’s dependencies and includes those dependencies in the program being compiled. The determination is made from “reference comments” and module import declarations as follows:

  • A comment of the form /// <reference path=”…’/> that occurs before the first token in a source file adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
  • A module import declaration that specifies a relative module name (section 11.3.1) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension ‘.ts’ exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension ‘.d.ts’ exists, that file is added as a dependency.
  • A module import declaration that specifies a top-level module name (section 11.3.1) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension ‘.ts’ or ‘.d.ts’ corresponding to the reference is located, that file is added as a dependency.

Any files included as dependencies in turn have their references analyzed in a transitive manner until all dependencies have been determined.