面试题答案
一键面试在TypeScript中,可以通过命名空间(Namespace)来组织代码,避免命名冲突。以下是示例代码:
- 定义不同命名空间下的
User
类:
// module1.ts
namespace CompanyA {
export class User {
constructor(public name: string) {}
greet() {
console.log(`Hello, I'm ${this.name} from CompanyA.`);
}
}
}
// module2.ts
namespace CompanyB {
export class User {
constructor(public name: string) {}
greet() {
console.log(`Hello, I'm ${this.name} from CompanyB.`);
}
}
}
- 使用这些类:
// main.ts
import { CompanyA, CompanyB } from './module1';
import { CompanyB as AnotherCompanyB } from './module2';
let userA = new CompanyA.User('Alice');
userA.greet();
let userB = new CompanyB.User('Bob');
userB.greet();
let anotherUserB = new AnotherCompanyB.User('Charlie');
anotherUserB.greet();
在上述代码中,CompanyA
和CompanyB
命名空间分别定义了User
类,通过命名空间的限定,避免了命名冲突。在使用时,通过完整的命名空间路径来引用对应的User
类。同时,为了展示不同模块中相同命名空间名的处理,在main.ts
中对CompanyB
进行了重命名(AnotherCompanyB
)来区分来自不同模块的同名命名空间。