在 TypeScript 中实例化一个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34317587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:51:42  来源:igfitidea点击:

Instantiating a Class in TypeScript

typescript

提问by superman1971

I have the following class structure

我有以下类结构

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;
}
}

and I create an instance of it in the usual way:-

我以通常的方式创建了一个实例:-

var chartOptions = new ChartingServices.ChartOptions();

I can set the property chartOptions.title with no problem at all.

我可以毫无问题地设置属性 chartOptions.title 。

However, I cannot get to the property chartOptions.myOptions.type and get an error about not being able to read property 'type' of undefined.

但是,我无法访问属性 chartOptions.myOptions.type 并收到关于无法读取未定义属性“类型”的错误。

Bearing in mind I have loads of classes, do I need to create an instance of each one to set / read properties. What can I do to get the code to work?

记住我有很多类,我是否需要为每个类创建一个实例来设置/读取属性。我该怎么做才能使代码正常工作?

回答by mk.

The first problem is that .myOptionsdoes not exist on chartOptions- you want options. You should capitalize all of your types: MyOptions, MyLegend, so that you do not confuse them with property names.

第一个问题是.myOptions不存在于chartOptions-你想要的options。您应该将所有类型大写:MyOptions, MyLegend,以免将它们与属性名称混淆。

The second problem is that although you instantiate a new ChartOptions:

第二个问题是,虽然你实例化了一个 new ChartOptions

var chartOptions = new ChartOptions();

...its optionsproperty isn't actually set to anything, and is therefore undefined. You need to set it either using a statement right after instantiation:

...它的options属性实际上并未设置为任何内容,因此未定义。您需要在实例化后立即使用语句设置它:

chartOptions.options = {type: "foo", ...other non-optional properties here}

Or in the constructor of ChartOptions, or via:

或在 的构造函数中ChartOptions,或通过:

options: MyOptions = {type: "foo", ...}

回答by billc.cn

TypeScript behaves similarly to the underlying JavaScript (and most other languages) in terms of object instantiation: all fields are initialised to undefinedunless you override it with a value.

在对象实例化方面,TypeScript 的行为类似于底层 JavaScript(和大多数其他语言):所有字段都被初始化为,undefined除非您用一个值覆盖它。

Also, there's no way to instantiate an interface. Instead you have to supply an object matching the signature. If you don't want to supply all the fields at the beginning, you can mark the fields in the interface with ?so they become optional, then you can do

此外,无法实例化接口。相反,您必须提供与签名匹配的对象。如果你不想在一开始就提供所有的字段,你可以在界面中标记字段,?使它们成为可选的,那么你可以这样做

export class ChartOptions {
    options: myOptions = {};
...