Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - difference between import ... and import {...} (with curly braces)

Coming from Java to TS, I've omitted the {...} around the imported type.

import DiscriminatorMappingData from './DiscriminatorMappingData'; 

instead of

import {DiscriminatorMappingData} from './DiscriminatorMappingData'; 

See TypeScript - storing a class as a map value?.

I've read the documentation and didn't understand much. I only took from it that when I only need one type from a file, I can omit the {}.
However, that caused weird errors, like "Unknown name", or unexpected type incompatibilites.

So, what's the difference, put simply?

like image 363
Ondra Žižka Avatar asked Aug 02 '16 20:08

Ondra Žižka


People also ask

Can I use import in TypeScript?

There are two ways to solve this: Using import = require() and setting the esModuleInterop property to true in the TypeScript Compiler configuration file. The import = require() syntax uses the exports object as the value for the import itself, allowing you to use each vector class.

What is {} in import?

The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.

What do curly braces mean in JavaScript?

Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.

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

The difference between your two import declarations is covered in the TypeScript specification. From §11.3.2, Import Declarations:

An import declaration of the form

import d from "mod";

is exactly equivalent to the import declaration

import { default as d } from "mod";

Thus, you would omit the braces only when you are importing something that was exported as the default entity of the module (with an export default declaration, of which there can only be one per module). The name you provide in the import declaration becomes an alias for that imported entity.

When importing anything else, even if it's just one entity, you need to provide the braces.

The Default exports section of the TypeScript handbook has a few examples.

like image 140
Michael Liu Avatar answered Oct 11 '22 06:10

Michael Liu