Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript, when to use reference, when to use import?

in TypeScript there are two concepts of referencing files/modules. Even though I went briefly through TypeScript documentation it is unclear to me, when which approach should be used when:

  1. Triple-Slash reference: /// <reference path="..." />
  2. Import: import { Foo } from "./Foo";

Thanks

like image 574
zuraff Avatar asked Aug 24 '16 10:08

zuraff


People also ask

What is reference in TypeScript?

Project references are a new feature in TypeScript 3.0 that allow you to structure your TypeScript programs into smaller pieces. By doing this, you can greatly improve build times, enforce logical separation between components, and organize your code in new and better ways.

Does TypeScript use import?

Importing TypesWith TypeScript 3.8, you can import a type using the import statement, or using import type .

What is import type in TypeScript?

import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there's no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript's output.


1 Answers

It is important to understand that these are not two concepts to reference files/modules. Their actually two completely different things.

import

This keyword was introduces in ES2015 and thus is part of its implementation, which is JavaScript. It doesn't only reference a file/module, but rather it reads the referenced module and makes its API/exposed stuff available to you.

Before import we had to use some sort of concat mechanism or use <link> in the HTML to get access to say jQuery. Now we can do import * as $ from 'jQuery' and JavaScript/TypeScript will "automatically" load the module for us. At least this is what it will do in the future as soon the Loader is finished.

If you're using TypeScript the TypeScript compiler will also know what types/signatures/... exported the code has.

/// <reference>

The little bit weird <reference> comment was used to pull in type definitions from external .d.ts files. But with a newer version of TypeScript you shouldn't need to do this anymore. You can read about the future of decalration files here.

So the difference between import and <reference> is that import will load the "real" code and make it available to you. <reference> on the other hand will only import type definitions for you. In your editor/IDE it will look like you're using the code, but actually TypeScript knows about the exposed APIs and pretends that actually can use the loaded module. It will be your job to make the module (globally) available when you want to run your code.

like image 154
Sebastian Sebald Avatar answered Sep 21 '22 20:09

Sebastian Sebald