简体   繁体   中英

Create a variable of certain type in typescript

I am trying to create variable in my component of certain type like below.

myrequest.model.ts
export class MyRequest {
    public endValue: string;
    public yearEnd: string;
}

In my component i import the above and do like below

myReqObj: MyRequest;

But if i try to do like

this.myReqObj.endValue = '23'

it trows a error like myReqObj is undefined. Am i doing the right way? What is the right way to do this.

Looks like you need to instantiate MyRequest. If you add a constructor, you can do this:

myReqObj: MyRequest = new MyRequest(null, null);
this.myReqObj.endValue = '23'

You should be defining the value as

this.myReqObj ={
      endValue : '23'
}

Updated : Use interface for custom types like these.

export interface MyRequest {
    endValue: string;
    yearEnd: string;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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