简体   繁体   English

在打字稿中创建某种类型的变量

[英]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. 它引发错误,例如myReqObj未定义。 Am i doing the right way? 我做对了吗? What is the right way to do this. 什么是正确的方法来做到这一点。

Looks like you need to instantiate MyRequest. 看起来您需要实例化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;
}

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

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