在TypeScript中实例化类
我的班级结构如下在TypeScript中实例化类,typescript,Typescript,我的班级结构如下 module ChartingServices { export class ChartOptions { options: myOptions; title: string; } export interface myOptions { colors: string[]; legend: myLegend; type: string; } export interface myLegend{ enabled: boolea
module ChartingServices {
export class ChartOptions {
options: myOptions;
title: string;
}
export interface myOptions {
colors: string[];
legend: myLegend;
type: string;
}
export interface myLegend{
enabled: boolean;
labelFormatter: string;
}
}
我以通常的方式创建了一个实例:-
var chartOptions = new ChartingServices.ChartOptions();
我可以毫无问题地设置属性chartOptions.title
但是,我无法访问属性chartOptions.myOptions.type并获取一个关于无法读取未定义的属性“type”的错误
记住我有很多类,我是否需要为每个类创建一个实例来设置/读取属性。如何才能使代码正常工作?TypeScript在对象实例化方面的行为与底层JavaScript(以及大多数其他语言)类似:所有字段都初始化为
未定义
,除非您使用值覆盖它
而且,没有方法实例化接口。相反,您必须提供与签名匹配的对象。如果不想在开始时提供所有字段,可以在界面中用?
标记字段,使其成为可选字段,然后可以这样做
export class ChartOptions {
options: myOptions = {};
...
第一个问题是
.myOptions
在图表选项
上不存在-您需要选项
。您应该大写所有类型:MyOptions
,MyLegend
,这样就不会将它们与属性名混淆
第二个问题是,尽管您实例化了一个新的图表选项
:
var chartOptions = new ChartOptions();
…其options
属性实际上没有设置为任何值,因此未定义。您需要在实例化后立即使用语句进行设置:
chartOptions.options = {type: "foo", ...other non-optional properties here}
或在图表选项的构造函数中,或通过:
options: MyOptions = {type: "foo", ...}
在我的例子中,我只需要检查特定的类。我使用了“constructor.name”,它在生产模式下崩溃
我在switch语句中使用了它,默认为error
switch (constructorInput.constructor.name) {
case 'A':
// do something
break;
case 'B':
// do something
break;
default:
throw new Error(constructorInput.constructor.name + ' is no valid Type');
}
我已经可以把它改成instanceof了
if (constructorInput instanceof A) {
// do something
} else if (constructorInput instanceof B) {
// do something
} else {
throw new Error('no valid Type');
}
这是生产和开发方面的工作。我已经做了,而且似乎效果很好。但是参考我的原始代码,在legend:myLegend上这样做有一个问题,因为您不能初始化接口成员。我是否需要将myLegend从接口更改为类?您的myLegend
选项与myOptions
相同。要么将它转换为一个类,每次构造一个新实例,要么将所有字段都设置为可选,并提供{}
作为初始值(就像我为上面的myOptions
建议的那样)。看起来您可以在类上执行此操作,但myLegend位于接口上,因此放置图例:myLegend={}不起作用。有什么想法吗?