Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Last active January 6, 2021 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aboglioli/17028f71497b385fba4c4eefc1f18263 to your computer and use it in GitHub Desktop.
Save aboglioli/17028f71497b385fba4c4eefc1f18263 to your computer and use it in GitHub Desktop.
Typescript class deserialization (using JSON.parse() and public properties)
const json = `{
"type": "two",
"value": 25.5,
"items": [{
"order": 2,
"value": "hello"
}, {
"order": 5,
"value": "bye"
}]
}`;
enum Type {
One = 'one',
Two = 'two',
Three = 'three',
}
class Item {
constructor(
public order: number,
public value: string,
) { }
}
class Data {
constructor(
public type: Type,
public value: number,
public items: Item[],
) { }
public doSomething(): void {
console.log('Doing...', this.type, this.value, this.items.length);
}
}
function main() {
const data: Data = JSON.parse(json);
console.log(data);
data.doSomething(); // ERROR: not really an instance
console.assert(data.type === Type.Two);
console.assert(data.value === 25.5);
console.assert(data.items.length === 2);
console.assert(data.items[0].order === 2);
console.assert(data.items[0].value === 'hello');
console.assert(data.items[1].order === 5);
console.assert(data.items[1].value === 'bye');
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment