by
81k 38
4
10
12k
1
Top 1% !
Popular
Famous
Pearl of Wisdom
Nice
Tagged
Easy-to-find
Specified
Refined
OpenSource
Popularity: 325th place
Created
Modified Sep 23, 2014

Published on:

Languagetypescript
libraryunderscore.js
LicenseMIT_X11
Technologynode.js

Typescript + underscore: serializing objects

This little example runs on node.js and assumes you have the typescript type-definition file in the types subdirectory.
 
The example defines two classes one representing a undergrad course in computer science and another one representing possible students for the course.

Few things are interesting here:
1 - the overloading of the toString() function so that our own version is called automatically
2 - the use of underscore .reduce to serialize the array
3 - the use of the constructor element to initialize Student instances
4 - the use of lambda expression 

overall we have a mixed object oriented and functional language here
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/32959/Typescript---underscore--serializing-obj?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
///<reference path='../types/node.d.ts'/> ///<reference path='../types/underscore.d.ts'/> import _ = require("underscore"); function write(msg) { process.stdout.write(msg+'\n'); } class Student { firstName : string; lastName : string; constructor( n: string, v: string ) { this.firstName = n; this.lastName = v; } toString() : string { return '[ ' + this.firstName + ' ' + this.lastName + ' ]'; } } class Class { title : string = "Computer Science 101"; participants : Student[] = new Array(); addStudent( s : Student ) : any { this.participants.push(s); } toString() : string { return this.title + '\n\t' + _.reduce( this.participants, (acc,s) => acc += '\n\t'+ s ); } } var firstSemesterClass : Class = new Class(); firstSemesterClass.addStudent( new Student("John","Smith")); firstSemesterClass.addStudent( new Student("Frank","Gehry")); write( firstSemesterClass );

Other Steps and Solutions

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus