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.
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.
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 .
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.
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();
}
}
myObj.myProperty
is type of A
which is not defined yet, so you should initialize it
myObj.myProperty = new A();
then use it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With