繁体   English   中英

一堆构造函数属性的TypeScript定义类型

[英]TypeScript Defining Type For Bunch Of Constructor Properties

我有以下代码,我想知道是否可以使用接口更有效地改进它,以减少类中构造函数属性的类型声明:

class sample {
sample1: string;
sample2: string;
sample3: number;
sample4: string[];
sample5: string;
sample6: string;
sample7: number;
sample8: string[];
sample9: string;
sample10: string;
sample11: number;
sample12: string[];

constructor (){
this.sample1= ''
this.sample2= ''
this.sample3= 2
this.sample4= [x,y,z]
this.sample5= ''
this.sample6= ''
this.sample7= 0
this.sample8= [a,b,c,d]
this.sample9= ''
this.sample10= 'sample';
this.sample11= 1;
this.sample12= [some,sample,text];
}

setSampleMethod = (text) => {
this.sample10 = text

}


}

无需使用接口,您可以创建一个在其中定义了getter / setter的模型类,然后将该模型扩展到您的类中。

请通过以下StackBlitz获取示例代码:
https://stackblitz.com/edit/angular-elss2i

在这里您可以看到,我还将默认值移到了构造函数的参数中。 这将帮助您在需要时将参数传递给构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM