typescript 中如何导出多个类型-ag捕鱼王app官网

typescript 中如何导出多个类型

作者:迹忆客 最近更新:2023/05/09 浏览次数:

使用命名导出来导出 typescript 中的多种类型,例如 export type a {}export type b {}。 可以使用命名导入作为 import {a, b} from './another-file' 来导入导出的类型。 我们可以在单个文件中拥有任意数量的命名导出。

这是从名为 another-file.ts 的文件中导出多种类型的示例。

another-file.ts

// 👇️ named export
export type employee = {
  id: number;
  salary: number;
};
// 👇️ named export
export type person = {
  name: string;
};

请注意,在类型定义所在的同一行使用 export 与在声明类型后将其导出为对象相同。

another-file.ts

type employee = {
  id: number;
  salary: number;
};
type person = {
  name: string;
};
// 👇️ named exports
export { employee, person };

以下是我们如何在名为 index.ts 的文件中导入类型。

index.ts

// 👇️ named imports
import { employee, person } from './another-file';
const employee: employee = {
  id: 1,
  salary: 500,
};
const person: person = {
  name: 'jim',
};

如果必须,请确保更正指向另一个文件模块的路径。 上面的示例假设 another-file.tsindex.ts 位于同一目录中。

例如,如果我们从一个目录向上导入,我们将 import {employee, person} from '../another-file'

我们在导入它们时将类型的名称包裹在花括号中——这称为命名导入。

typescript 使用模块的概念,就像 javascript 一样。

为了能够从不同的文件中导入类型,必须使用命名或默认导出来导出它。

上面的示例使用命名导出和命名导入。

命名导出和默认导出和导入之间的主要区别是 - 每个文件可以有多个命名导出,但只能有一个默认导出。

如果我们尝试在单个文件中使用多个默认导出,则会收到错误消息。

another-file.ts

type employee = {
  id: number;
  salary: number;
};
type person = {
  name: string;
};
// ⛔️ error: a module cannot
// have multiple default exports.ts(2528)
export default employee;
export default person;

typescript a module cannot have multiple default exports

重要提示 :如果要将类型或变量(或箭头函数)导出为默认导出,则必须在第一行声明它并在下一行导出。 我们不能在同一行声明和默认导出变量。

话虽如此,我们可以在单个文件中使用 1 个默认导出和任意数量的命名导出。

让我们看一个导出多种类型并同时使用默认导出和命名导出的示例。

another-file.ts

type employee = {
  id: number;
  salary: number;
};
// 👇️ named export
export type person = {
  name: string;
};
// 👇️ default export
export default employee;

以下是我们将如何导入这两种类型。

index.ts

import employee, { person } from './another-file';
const employee: employee = {
  id: 1,
  salary: 500,
};
const person: person = {
  name: 'jim',
};

请注意,我们没有将默认导入包含在花括号中。

我们使用默认导入来导入 employee 类型,并使用命名导入来导入 person 类型。

每个文件只能有一个默认导出,但可以根据需要拥有任意数量的命名导出。

根据我的经验,大多数现实世界的代码库都专门使用命名导出和导入,因为它们可以更轻松地利用您的 ide 进行自动完成和自动导入。

我们也不必考虑使用默认导出或命名导出来导出哪些成员。

上一篇:

下一篇:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 typescript 中返回一个 promise

发布时间:2023/03/19 浏览次数:586 分类:typescript

本教程讨论如何在 typescript 中返回正确的 promise。这将提供 typescript 中 returns promise 的完整编码示例,并完整演示每个步骤。

在 typescript 中定义函数回调的类型

发布时间:2023/03/19 浏览次数:1445 分类:typescript

本教程说明了在 typescript 中为函数回调定义类型的ag捕鱼王app官网的解决方案。为了程序员的方便和方便,实施了不同的编码实践指南。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图