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

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

问题描述

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

import DiscriminatorMappingData from './DiscriminatorMappingData';

代替

import {DiscriminatorMappingData} from './DiscriminatorMappingData';

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

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

那么,简单地说,有什么区别?

解决方案

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

<块引用>

表单的导入声明

从mod"导入d;

完全等同于导入声明

import { default as d } from "mod";

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

导入其他任何东西时,即使只是一个实体,也需要提供大括号.

TypeScript 手册的默认导出部分有一些示例.>

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?

解决方案

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.

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

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