tl;dr: My goal is to apply compiled Typescript prototype definitions to objects I have defined as classes.
Situation:
I am looking to enhance a JavaScript object with business logic specified in a typescript class.
For example:
class Address
{
constructor(
public Street: string,
public Number: number,
public Zip: number,
public City: string)
{ }
public get FullAddress()
{
return this.Street + ' ' + this.Number + ', '
+ this.Zip + ' ' + this.City;
}
}
The compiled JS code adds the extension to the object prototype using FullAddress
. When calling
new Address('Somestreet', 5, 3564, 'SomeCity')
everything works smoothly.
The Problem: When receiving a JS object (e.g., via angular's $http
)
$http.get('/api/address').then((answer: AngularPromise<Address[]>) =>
{
console.log(answer.data[0].FullAddress());
});
The issue arises when trying to call FullAddress
on the object because Typescript merely defines it in the class without modifying the actual object.
Attempted Solution: One workaround could be to instantiate each object individually as shown below:
$http.get('/api/address').then((answer: AngularPromise<Address[]>) =>
{
for(var i = 0; i < answer.data.length; i++)
{
answer.data[0] = new Address(answer.data[0].Street, ans.....);
}
console.log(answer.data[0].FullAddress());
});
This approach may involve overloading the Address
constructor to accept the complete object to minimize redundancy.
The actual Question: Given that the object structure I require is more intricate than the simplistic Address example provided here, the above solution would lead to excessive boilerplate. I am seeking a more efficient way to address this dilemma.