ts-object-create
v0.4.3
Published
Object creation that utilizes type information
Downloads
17
Readme
TsObjectCreate
This is a very experimental library that uses code generation to create functions for creating objects. Currently it doesn't work in many scenarios so just don't use this yet.
Example
Setup
Say you have some classes like this:
// ./src/classes.ts
export class Main {
name: string;
other: Other;
}
export class Other {
prop: string;
}
You could generate some code based on these classes:
import * as fs from "fs";
const code = getGeneratedCode({
srcRoot: "./src"
files: ["./src/classes.ts"]
});
fs.writeFile("./src/objectFactory.ts", code);
Use
Then this would allow you to do the following:
// ./src/main.ts
import * as objectFactory from "./objectFactory";
import {Other, Main} from "./classes";
const main = objectFactory.Classes.Main.create({
name: "my name",
other: {
prop: "my prop string"
}
});
main instanceof Main; // true
main.other instanceof Other; // true
// serialize it
const json = JSON.stringify(main);
// deserialize it
const newMain = objectFactory.Classes.Main.create(JSON.parse(json));
newMain instanceof Main; // true
newMain.other instanceof Other; // true