How can you allow classes defined in a module to be accessible outside of the module?
How can you allow classes defined in a module to be accessible outside of the module?
To allow classes defined in a TypeScript module to be accessible outside of the module, you need to use the export
keyword. This keyword makes the classes, along with any other variables, functions, or interfaces you choose, accessible from other modules by explicitly exporting them.
Here's a step-by-step explanation and example:
In your TypeScript module, define the class you want to be accessible outside the module and prefix it with the export
keyword. This makes the class public, allowing it to be imported by other modules.
Example:
// file: University.ts
export class Student {
constructor(public name: string, public age: number) { }
}
Once the class is exported, you can import it into another TypeScript file using the import
statement. Specify the name of the class and the relative path to the module file where the class is defined.
Example:
// file: App.ts
import { Student } from './University';
let student = new Student("John Doe", 22);
console.log(student);
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào