Reputation: 5624
Lets say I have a class A
like this:
export class A extends Observable {
constructor(
public id: string
) { super(); }
public testCallFunction() {
return "Function called on object with id " + this.id;
}
}
I can initialise an array of A
like this and the function is exposed:
this.data = [new A("1"), new A("2")];
When I initialise the array like this, it does not let me call the function due to "type error":
this.data = [{ "id": "1" }, { "id": "2" }] as Array<A>;
// ERROR TypeError: a.testCallFunction is not a function
Is there anyway I can use the second way of initialising the array and also expose the functions?
Where can I read more about this behaviour?
Playground: https://play.nativescript.org/?template=play-ng&id=G7b4f4&v=3
Upvotes: 0
Views: 40
Reputation: 28138
This is because when you use an Object literal, you have to create all the properties and methods of A, before typescript can accept that your object is of type A.
This is why you create intances with new
. Now you automatically get all the properties and methods.
class A {
private id: string
constructor(id: string) {
this.id = id
}
public testCallFunction() {
return "Function called on A instance"
}
}
class Test {
private data: A[];
constructor() {
this.data = [new A("1"), new A("2")]
// typescript does not recognise this object
// as an A instance because it has no testcallFunction
// this.data = [{ "id": "1" }, { "id": "2" }]
var a:A = this.data[0]
a.testCallFunction()
}
}
UPDATE
You can use Object.assign()
to add properties from JSON to an existing instance.
class A {
public id: string
public testCallFunction() {
console.log("my id is " + this.id)
}
}
let a = new A()
let json = { "id": "1" }
Object.assign(a, json)
console.log("id is now " + a.id)
a.testCallFunction()
Upvotes: 1