简体   繁体   English

TypeScript类和接口

[英]TypeScript classes and interfaces

I have the following typescript code:- 我有以下打字稿代码:

    export class Parent {
    name: string;
    details: Details = {};
}

export interface Details {
    age?: number;
    address?: Address};
}

export interface Address {
    address1: string;
    address2: string;
}

Then I can reference this code to set some values:- 然后,我可以参考此代码来设置一些值:

var myOptions = new HSCIC.Visualisation.Services.Parent();

myOptions.name = "Chris";
myOptions.details.age = 25;
myOptions.details.address.address1 = "10 The Lane";

The first two setters are working fine but I get a 'Cannot set property 'address1' of 'undefined'. 前两个设置器工作正常,但是我得到的“无法设置属性'address1'为'undefined'。

If I can set the age property from Details, then why can't I set the address1 property of Address, and how can I fix it? 如果可以从“详细信息”中设置age属性,那么为什么不能设置Address的address1属性,如何解决呢?

Because you wrote: 因为您写道:

address?: Address};

But for the code to be valid, it should be: 但是,要使代码有效,应为:

address?: Address = {address1: null, address2: null};

You need to assign a value to address, just like you did in details: Details = {}; 您需要为地址分配一个值,就像您在details: Details = {};所做的一样details: Details = {}; , or it will be undefined. ,否则它将是未定义的。 To do it this way, Details would need to be defined as a class, not an interface. 为此,需要将Details定义为一个类,而不是一个接口。 Writing : Address does not instantiate a new class, it only specifies the type. 编写: Address不会实例化新类,它仅指定类型。 Alternatively, you can make address1 and 2 optional like you did address, using ? 另外,您可以像使用地址一样将address1和2设为可选? , and then just write address?: Address = {}; ,然后只写address?: Address = {};

If you don't want to define Details as a class, you could write details: Details = {address:{}}; 如果您不想将Details定义为一个类,则可以编写details: Details = {address:{}}; under Parent. 在父项下

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

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