Typescript-如何访问通过命名空间声明的类?
一个初学者的快速问题。我目前正在寻找减少项目中“导入”数量的方法,偶然发现了本教程- 它建议使用名称空间来公开接口,如下所示Typescript-如何访问通过命名空间声明的类?,typescript,object,interface,namespaces,Typescript,Object,Interface,Namespaces,一个初学者的快速问题。我目前正在寻找减少项目中“导入”数量的方法,偶然发现了本教程- 它建议使用名称空间来公开接口,如下所示 namespace ApiModel { export interface Customer { id: number; name: string; } export interface User { id: number; isActive: boolean; } } 这
namespace ApiModel {
export interface Customer {
id: number;
name: string;
}
export interface User {
id: number;
isActive: boolean;
}
}
这就是我应该如何使用不同文件中的接口
export class MyComponent {
cust: ApiModel.Customer;
}
看起来不错,但有一件事我还是不明白如何删除Customer类的新实例并为其分配一些属性?如何为对象分配属性,就像在本例中,该对象只是名称空间的属性
非常感谢如何声明Customer类的新实例并为其分配一些属性? 要声明类的新实例,首先需要声明实现接口的类:
namespace MyNamespace {
export interface ICustomer {
id: number;
name: string;
}
}
class Customer implements MyNamespace.ICustomer {
id: number;
name: string;
constructor(id: number, name, string) {
this.id = id;
this.name = name;
}
}
const customer = {
id: 1, name: "Mr. Bean"
} as MyNamespace.ICustomer;
现在可以实例化Customer
类
如何将属性分配给对象(在本例中,该对象只是名称空间的属性?
命名空间没有属性。类和接口执行可能位于命名空间下的操作。您可以创建一个customer
对象,该对象具有与接口相同的属性:
namespace MyNamespace {
export interface ICustomer {
id: number;
name: string;
}
}
class Customer implements MyNamespace.ICustomer {
id: number;
name: string;
constructor(id: number, name, string) {
this.id = id;
this.name = name;
}
}
const customer = {
id: 1, name: "Mr. Bean"
} as MyNamespace.ICustomer;
类型化系统是结构化的,而不是名义上的,不像C或C++。这就是为什么您可以创建
customer
,因为对象结构是相同的
希望这有帮助 您是否声明了一个实现
Customer
接口的Customer
类?我尝试过,但不知道如果该类的属性实际上是另一个对象,如何扩展该类。你能告诉我吗?哪一处房产是实物?我只看到数据类型。。。字符串、数字和布尔值。根据上面的教程,要使用该接口,我需要以下代码:导出类MyComponent{cust:ApiModel.Customer;usr:ApiModel.User}现在我可以创建MyComponent的新实例,但是我不能像这样给它赋值——可能是因为我还需要创建cust var mycop=new JWTComponent的一些实例;mycop.cust.id=“1”;}