Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to reference TypeScript definition in every file?

Is there a way to tell TypeScript to use a certain file (or set of files) as a definition for everything compiled?

My only alternative currently is to add something like this in every single TypeScript file (which seems clunky):

/// <reference path="DefinitelyTyped/requirejs/require.d.ts" /> 
like image 313
HotStuff68 Avatar asked Mar 11 '15 14:03

HotStuff68


People also ask

What is the purpose of a TypeScript declaration file?

Declaration files, if you're not familiar, are just files that describe the shape of an existing JavaScript codebase to TypeScript. By using declaration files (also called . d. ts files), you can avoid misusing libraries and get things like completions in your editor.

Are TS files TypeScript?

TypeScript has two main kinds of files. . ts files are implementation files that contain types and executable code. These are the files that produce . js outputs, and are where you'd normally write your code.

What are triple slash directives in TypeScript?

Triple-slash directives are single-line comments containing a single XML tag. The contents of the comment are used as compiler directives. Triple-slash directives are only valid at the top of their containing file.


1 Answers

When using TypeScript's internal module system, you can avoid having any <reference> tags at all in the code. I personally do this because I don't want to encode paths (realtive or absolute) within the code as I constantly move stuff around.

One way to do this is by making sure all required declaration files and TypeScript source files are passed to the compiler as arguments during compile time.

Using gulp together with gulp-typescript simplifies this task. You can set noExternalResolve in gulp-typescript to true, and create gulp tasks that take all your .d.ts files along with your sources and pipe it down to the compiler. When you pull in tsd into your stack, you only need to pass the tsd.d.tsfile that contains references to all other definition files installed via tsd.

UPDATE for TypeScript >= v1.5: you can use a tsconfig.json file, and the compiler will get the ordering of the classes right. This removes the need to use gulp-typescript alltogether. You can either chose to have all files explicitly listed in the tsconfig.json file, or completely leave out the files property to include all *.ts/*.tsx files within the directory the tsconfig.json resides (including all subfolders).

A sample tsconfig.jsonmay look like:

{     "compilerOptions": {         "target": "ES5",         "module": "commonjs",         "lib": [ "es5", "es2015.promise", "dom" ]     },     "include": [         "src/**/*.ts"     ] } 
like image 62
Dynalon Avatar answered Sep 20 '22 22:09

Dynalon