TypeScript-import ...和import {...}(带花括号)之间的区别 [英] TypeScript - difference between import ... and import {...} (with curly braces)

查看:937
本文介绍了TypeScript-import ...和import {...}(带花括号)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Java到TS,我省略了导入类型周围的{...}.

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

import DiscriminatorMappingData from './DiscriminatorMappingData';

代替

import {DiscriminatorMappingData} from './DiscriminatorMappingData';

请参见 TypeScript-将类存储为地图值?.

我已经阅读了文档,但不太了解.我只是从中得出的结论是,当我只需要文件中的一种类型时,可以省略{}.
但是,这导致了奇怪的错误,例如未知名称"或意外的类型不兼容.

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?

推荐答案

TypeScript规范涵盖了两个import声明之间的差异.从§11.3.2起,导入声明:

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";

完全等同于导入声明

import { default as d } from "mod";

因此,在导入以模块的default实体(带有export default声明,其中只能有一个)导出的内容时,您将仅省略括号 .每个模块).您在import声明中提供的名称将成为该导入实体的别名.

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.

TypeScript手册的默认导出部分提供了一些示例.

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

这篇关于TypeScript-import ...和import {...}(带花括号)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆