Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript var vs import

Tags:

In TypeScript, what is the difference between

 import http = require('http'); 

and

 var http = require('http'); 

I am seeing both ways being used in code source, are they interchangeable?

like image 690
mfc Avatar asked Apr 25 '15 00:04

mfc


People also ask

How do I import a variable in TypeScript?

To import a variable from another file in TypeScript: Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import { str } from './another-file' .

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.

What is the difference between require and import in TypeScript?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with .


1 Answers

Your import statement is TypeScript and will not run as-is in Node. You will need to compile (transpile?) it to JavaScript first. You can read the TypeScript docs for more info about how the TypeScript import keyword works. See the "Using Modules" subsection of the "Namespaces and Modules" section of the TypeScript handbook.

There is an import keyword in JavaScript too, but it doesn't work the way TypeScript's import works. It will only work in versions of Node that support ES6 modules. There are differences between this import and require that you can read about at "ES6 Modules: The Final Syntax". That import is something you can compare/contrast with require but not really var.

like image 75
Trott Avatar answered Oct 04 '22 14:10

Trott