fe-interview
fe-interview copied to clipboard
[TypeScript] 第1540天 在TypeScript中如何访问模块外定义的类?
在TypeScript中,要访问模块外定义的类,需要确保该类是可以导出的,并且在需要使用的地方正确地导入。以下是一个具体的示例,演示如何在不同的文件和模块中定义和访问类。
1. 定义和导出类
首先,在一个文件中定义并导出一个类。假设文件名为 Person.ts:
// Person.ts
export class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
2. 导入和使用类
在另一个文件中,可以通过 import 语句来导入并使用这个类。假设文件名为 main.ts:
// main.ts
import { Person } from './Person';
const john = new Person('John Doe', 30);
john.greet(); // 输出: Hello, my name is John Doe and I am 30 years old.
3. 使用默认导出(可选)
你也可以使用默认导出,在导入时会有略微不同的语法。修改 Person.ts 文件:
// Person.ts
export default class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
在 main.ts 文件中导入默认导出的类:
// main.ts
import Person from './Person';
const jane = new Person('Jane Doe', 25);
jane.greet(); // 输出: Hello, my name is Jane Doe and I am 25 years old.
4. 使用命名空间(可选)
如果你想将多个类或接口组织在一个命名空间中,可以使用 namespace 关键字。以下是一个示例:
定义命名空间并导出类
// MyNamespace.ts
export namespace MyNamespace {
export class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
}
导入命名空间中的类
// main.ts
import { MyNamespace } from './MyNamespace';
const alice = new MyNamespace.Person('Alice', 28);
alice.greet(); // 输出: Hello, my name is Alice and I am 28 years old.
总结
在TypeScript中,要访问模块外定义的类,需要遵循以下步骤:
- 在类定义的文件中使用
export导出类。 - 在需要使用类的文件中使用
import导入类。 - 确保文件路径和文件扩展名正确(如果使用模块解析,扩展名可以省略)。
使用这些方法,你可以轻松地在不同模块和文件之间共享和访问类。