greenchapter
greenchapter

Reputation: 136

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'; in my Service. With the next step I declare a var earth with the type any, that will work.

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

I got the following error:

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

Whats the right way to do get the class as type?

Upvotes: 1

Views: 58

Answers (1)

Nicholas K
Nicholas K

Reputation: 15423

Just use

private earth: Data;

The statement private earth: <Data> isn't valid typescript syntax.


Furthermore, if you intended to use generics then you can use 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.

export class Data<T> {

 ...

}

Upvotes: 1

Related Questions