Reputation: 18719
I am having little issue with TypeScript. I have a module, where I have defined two classes (I will provide code below). I cannot access other class, inside the first one, and the opposite. What am I doing wrong?
Here is my code:
module Model {
export class Model {
public apples:Apple[];
getAppleCnt() {
return this.model.apples.length;
}
createApple(){
var index = this.model.apples.getAppleCnt()+1;
return this.model.apples.push(Apple.createApple("Apple "+index,index));
}
createApples(){
this.model = new Model();
this.model.apples.=[];
}
}
export class Apple {
createApple(name:string,index:number){
var apple = new Apple();
apple.name = name;
apple.index = index;
return apple;
}
}
}
Upvotes: 1
Views: 66
Reputation: 276303
Here is one way to do it:
module Model {
export class Model {
public apples: Apple[];
getAppleCnt() {
return this.apples.length;
}
createApple() {
var index = this.getAppleCnt() + 1;
return this.apples.push(Apple.createApple("Apple " + index, index));
}
createApples() {
this.apples = [];
}
}
export class Apple {
name: string;
index: number;
static createApple(name: string, index: number) {
var apple = new Apple();
apple.name = name;
apple.index = index;
return apple;
}
}
}
Upvotes: 2
Reputation: 123901
We should either create an instance of the Apple or call static method:
module Model {
export class Model {
protected model: Model;
public apples:Apple[];
getAppleCnt() {
return this.model.apples.length;
}
createApple(){
var index = this.model.apples.length + 1;
// instance
var apple = new Apple().createApple("Apple "+index,index);
// or call some static method
apple = Apple.createAppleStatic("Apple "+index,index);
return apple;
}
createApples(){
this.model = new Model();
this.model.apples = [];
}
}
export class Apple {
public name: string;
public index: number;
createApple(name:string,index:number){
var apple = new Apple();
apple.name = name;
apple.index = index;
return apple;
}
// the same as above but static one
static createAppleStatic(name:string,index:number){
var apple = new Apple();
apple.name = name;
apple.index = index;
return apple;
}
}
}
There is a working playground example
Upvotes: 1