Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use class variables in object in typescript?

suppose I have a class in typescript file like below:

export class app {
  public variable1: string;
  public variable2: number;
  public variable3 = "Hello world"
  constructor(count: number) {
      this.variable1 = "something",
      this.variable2 = 1 + count;
   }

}

now in another file, I am exporting this class as:

import { app } from './directory';
let pageApp:app;

now, how can I access app variables here?

like image 744
Kazi Avatar asked Jul 24 '18 12:07

Kazi


2 Answers

Your definition of the class is syntactically incorrect, no let in classes and semantically incorrect, you need to declare all fields:

// appClass.ts
export class app {
    variable1: string // implicitly public in typescript
    variable2: number
    variable3 = "Hellow world"
    constructor(count : number) {
        this.variable1 = "something";
        this.variable2 = 1 + count;
    }

} 

With regard to usage, the import should be fine, but you need to import the file in which the class resides (not the directory as your imports suggest) and you need to new up the class to create an instance

import { app } from './appClass'; // notice no extension (no .js or .ts)
let pageApp:app = new app(1);
console.log(pageApp.variable2);
like image 184
Titian Cernicova-Dragomir Avatar answered Sep 19 '22 23:09

Titian Cernicova-Dragomir


Reference --> Typescript classes

Let's say you class as:

export class app {
   //you can specify Public, private, and protected modifiers
   // default consider as public so you can access in other class as well.

   public variable1="Hellow world";
   public variable2: any
   public variable3: any;

  constructor(count){
      this.variable1="something",
      this.variable2=1+count;
   }
}

import in another file

import { app } from './directory';
let var_name = new app('pass_count_here')

//Access
var_name.variable1
like image 34
Akj Avatar answered Sep 22 '22 23:09

Akj