使用 TypeScript 从另一个文件导入类型
Import a Type from Another file using TypeScript
要从 TypeScript 中的另一个文件导入类型:
- 从文件中导出类型
A
,例如export type Employee = {}
。 - 将文件中的类型导入
B
为import { Employee } from './another-file';
. - 使用文件中的类型
B
。
下面是从名为another-file.ts
.
// 👇️ named export export type Employee = { id: number; name: string; salary: number; };
以下是我们如何将Employee
类型导入
名为index.ts
.
// 👇️ named import import { Employee } from './another-file'; const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp);
如果必须,请确保更正指向another-file
模块的路径。上面的示例假定another-file.ts
和index.ts
位于同一目录中。
例如,如果another-file.ts
位于上一级目录,则必须导入为import {Employee} from '../another-file'
.
TypeScript 使用
模块的概念,就像 JavaScript 一样。
您可能还会看到在导入时明确使用type
关键字的示例。
// 👇️ explicitly importing type import type { Employee } from './another-file'; const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp);
您只能import type
在导入类型和接口时使用语法。
import type
syntax is mostly used to get around some circular import errors caused by importing types between the same files.The examples above use named exports and named imports.
The main difference between named and default exports and imports is – you can
have multiple named exports per file, but you can only have a single default
export.
Let’s look at an example of how we would import a type that was exported using a
default export.
Here are the contents of another-file.ts
.
type Employee = { id: number; name: string; salary: number; }; // 👇️ default export export default Employee;
And here is how we would import the type using a default import.
// 👇️ default import import Employee from './another-file'; const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp);
Notice that we didn’t wrap the import in curly braces.
We could have also used a different name when importing the type, e.g. Foo
.
// 👇️ default import import Foo from './another-file'; const emp: Foo = { id: 1, name: 'James', salary: 100, }; console.log(emp);
This works, but is confusing and should be avoided.
You also don’t have to think about which members are exported with a default or named export.
You can also mix and match. Here is an example of a file that uses both a
default and a named export.
type Employee = { id: number; name: string; salary: number; }; // 👇️ default export export default Employee; // 👇️ named export export type Person = { name: string; };
And here is how you would import the two types.
// 👇️ default and named imports import Employee, { Person } from './another-file'; const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp); const person: Person = { name: 'Carl', }; console.log(person);
We used a default import to import the Employee
type and a named import to
import the Person
type.
Note that you can only have a single default export per file, but you can have
as many named exports as necessary.