MST

星途 面试题库

面试题:TypeScript中Namespace的基本使用

在TypeScript项目中,简述如何创建一个Namespace,并在其中定义接口和类,然后在外部调用这个Namespace中的类。
40.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 创建命名空间并定义接口和类
    // 创建一个命名空间
    namespace MyNamespace {
        // 定义接口
        export interface IMyInterface {
            prop1: string;
            method1(): void;
        }
        // 定义类实现接口
        export class MyClass implements IMyInterface {
            prop1: string;
            constructor(prop1: string) {
                this.prop1 = prop1;
            }
            method1(): void {
                console.log(`This is method1 in MyClass, prop1 is ${this.prop1}`);
            }
        }
    }
    
  2. 在外部调用命名空间中的类
    // 引入命名空间
    import { MyClass } from './yourFilePath';// 根据实际文件路径引入
    // 创建类的实例并调用方法
    const myInstance = new MyClass('example value');
    myInstance.method1();
    

在上述代码中,首先在MyNamespace命名空间内定义了IMyInterface接口和实现该接口的MyClass类。然后在外部通过import语句引入该命名空间中的MyClass类,并创建实例调用其方法。注意import语句中的文件路径要根据实际情况进行调整。