I'm trying to add a computed property to a array of typed objects I'm getting (from a server).
I've built a simplified example that i think is similar to my case:
in this example, I'm trying to use a property of ClassA to cucullate a property and add it to ClassB, and when i'll have objects of type ClassA I could hopefully cast them to ClassB, and the required property will be calculated and added to it.
export class ClassA {
title = 'a1';
}
export class ClassB extends ClassA {
foo(){
return this.title+'a';
}
someProperty = this.foo();
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'classExtenstionTest';
x = new ClassA;
xx= this.x as ClassB; //can i do this?
ngOnInit() {
console.log(this.x);// return properties of class A
console.log(this.xx); //also returns properties of class A (and not ClassB), why?
}
}
but it doesn't seem to work, I cant get the required properties of ClassB after the casting. I'm fairly new to typescript, any help will be appreciated, thanks!
The as
keyword in TypeScript is not doing what you think it is.
It is only syntax for the transpiler to ignore type checking and not "casting" like in Java for instance.
A better explanation of as
in TypeScript here: https://stackoverflow.com/a/55781571/4529555
There are many different ways to achieve what you want.
Why not use the constructor of ClassB
and pass the concrete instance of ClassA?
export class ClassA {
title = 'a1';
}
export class ClassB extends ClassA {
constructor(objectA: ClassA) {
super();
this.title = objectA.title
}
foo(){
return this.title+'a';
}
someProperty = this.foo();
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'classExtenstionTest';
private x = new ClassA();
private xx= new ClassB(this.x);
ngOnInit() {
console.log(this.x);
console.log(this.xx);
}
}