Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a class as a type for properties of another class in typescript?

I am new to typescript. I have defined some classes. I have used them as a type for the property of another class. e.g:

fileone.ts

export class A {
   propertyOne: string;
   propertyTwo: string;
}

Now i have another class B in another file:

filetwo.ts

import { A } from './fileone';
export class B {
    myProperty: A;
    mySecondProperty: string;
}

I have instantiated this class B in another file. I have the following code:

myapp.ts

import { B } from './filetwo';
export class C {
    let myObj: B = new B();
    myObj.myProperty.propertyOne = 'hello';
    myObj.myProperty.propertyTwo = 'world'';
    console.log(myObj);
 }

Now when i try to set the property of A through B, it say the following error:

Cannot set the property "propertyOne" of undefined

Can we not do this like in java? And please explain why i cannot do what i am doing right now. And what is the correct approach for this. Please do not just give me solution to my problem but also an explanation.

like image 392
kanra-san Avatar asked Dec 09 '16 10:12

kanra-san


People also ask

How do I use a class in another class in TypeScript?

You can do this by using the new keyword, followed by a syntax similar to that of an arrow function, where the parameter list contains the parameters expected by the constructor and the return type is the class instance this constructor returns. The TypeScript compiler now will correctly compile your code.

Can we use class as type in TypeScript?

TypeScript treats a class as both value and type. This implicit type declared by TypeScript describes the shape of the instance a class produces. Therefore when a class is used as a type, such as using let value :Class annotation, TypeScript checks if the value has all the public properties of the Class .

How do I inherit a class in TypeScript?

A class inherits from another class using the 'extends' keyword. Child classes inherit all properties and methods except private members and constructors from the parent class.


2 Answers

You have set the correct type of your myProperty member but this variable is not initialized by just declaring the type. So you are trying to set a property propertyOne on an undefined variable on your instance of B.

If you want to have it initialized correctly, you need to do this manually in your class B:

export class B {
  myProperty: A;
  constructor() {
    this.myProperty = new A();
  }
}
like image 61
Andreas Jägle Avatar answered Sep 17 '22 14:09

Andreas Jägle


myObj.myProperty is type of A which is not defined yet, so you should initialize it

myObj.myProperty = new A();

then use it

like image 43
asdf_enel_hak Avatar answered Sep 17 '22 14:09

asdf_enel_hak