面试题答案
一键面试- 创建命名空间并定义接口和类:
// 创建一个命名空间 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}`); } } }
- 在外部调用命名空间中的类:
// 引入命名空间 import { MyClass } from './yourFilePath';// 根据实际文件路径引入 // 创建类的实例并调用方法 const myInstance = new MyClass('example value'); myInstance.method1();
在上述代码中,首先在MyNamespace
命名空间内定义了IMyInterface
接口和实现该接口的MyClass
类。然后在外部通过import
语句引入该命名空间中的MyClass
类,并创建实例调用其方法。注意import
语句中的文件路径要根据实际情况进行调整。