简体   繁体   English

用类声明变量

[英]Declare a variable with a class

I try around with storing data in a model.我尝试在模型中存储数据。 For that I created a class, which looks like that:为此,我创建了一个类,如下所示:

export class Data {
  constructor(moons: number, color: string) {
    this.moons = moons;
    this.color = color;
  }

  moons: number;
  color: string;
}

I import the class with import { Data } from './data.model';我使用import { Data } from './data.model';导入类import { Data } from './data.model'; in my Service.在我的服务中。 With the next step I declare a var earth with the type any , that will work.在下一步中,我声明了一个类型为any的 var earth ,这将起作用。

export class DataService {
  private earth: any;

  constructor() {
    this.earth = new Data(1, 'blue');
  }
}

But I want to set this variable to the class type Data.但我想将此变量设置为类类型数据。 But it doesn't work when I set private earth: <Data>;但是当我设置private earth: <Data>;时它不起作用private earth: <Data>;

I got the following error:我收到以下错误:

10:24 - error TS1005: '(' expected.

Whats the right way to do get the class as type?将类作为类型的正确方法是什么?

Just use只需使用

private earth: Data;

The statement private earth: <Data> isn't valid typescript syntax.声明private earth: <Data>不是有效的打字稿语法。


Furthermore, if you intended to use generics then you can use Data<any> .此外,如果您打算使用泛型,那么您可以使用Data<any> It signifies that the class accepts a generic type and would mean that it should be defined as below in order for private earth: Data<any> to work.它表示该类接受泛型类型,这意味着它应该如下定义以便private earth: Data<any>工作。

export class Data<T> {

 ...

}

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

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