Using Typescript interface constructor to modify objects at runtime

This demo will show how to use TypeScript's interface constructor to create a generic method to modify your typescript objects at runtime.

Since I won't go into details in this post about cloning objects in TypeScript, I made  sure the code is documented enough for any developer to understad.

interface Cloner<T> {
//note the new() T inside of the interface
new(): T;
[key: string]: any;
}
function Clone<T>(octor: Cloner<T>, props: any): T {
let oct = new octor();
for (const [key, value] of (<any>Object).entries(props)) {
(<any>oct)[key] = value;
}
return oct;
}
//class used to clone
class Person {
//props
public fullName: string
//required to inject or add additional methods and properties to the person object at runtime
[key: string]: any;
constructor() {
this.fullName = '';
}
//implementation here
}
//using the code
let c1 = Clone(Person, {
firstname: "John",
lastname: "Doe",
role: "Developer",
languages: ["C#, Javascript", "HTML"],
sayHello: function (msg: string): string {
return `${this.role} ${msg} there!`;
}
});
let c2 = Clone(Person, {
firstname: "Jane",
lastname: "Doe",
role: "Developer",
languages: ["C#, Javascript", "HTML", "Node"],
sayHello: function (msg: string): string {
return `${msg} there, ${this.fullName}`;
}
});

c1["firstname"]; //?
c1["role"]; //?
c1.firstname; //?
c1.role; //?
c1.languages; //?
c1.sayHello("Hello"); //?
c1.languages.push("Golang");
const l1 = c1.languages;
l1; //?
const l2 = c2.languages;
l2;
let c3 = Clone(Person, {
firstname: "Jane",
lastname: "Doe",
role: "Developer",
languages: ["C#, Javascript", "HTML", "Node"],
greet: function (greeting: string): string {
return `${greeting} there, ${this.firstname} ${this.lastname}`;
}
});
console.log(c3 === c2);
console.log(c1 === c3)
console.log(c2.sayHello("Hi"));
console.log(c1 instanceof Person);
console.log(typeof c1)
c2.fullName = `${c2.firstname} ${c2.lastname}`
console.log(c2.fullName)
console.log(c3.greet('Hello'))


You can read more about TypeScript interfaces on https://basarat.gitbooks.io/typescript/docs/types/interfaces.html

Comments are closed