2013-10-25

As a developer I hate loosely typed data. When I  have started playing with Sharepoint Hosted apps and had to use JavaScript, one of my pain points was the common SharePoint pain – loosely typed data. I mean, that you have you SP.ListItem, and you cannot check if you did not make a misprint, no one tells you that is is  better to use listitem.get_item(“yourmegafield”) instead of listitem[“yourmegafield”]. So I was looking into TypeScript for the reason that you might have need to make a strongly typed data.

So I made a little demo and a little class that demonstrates how you could work with strong types. I have a list that has a title and a number. So I want to work with the list in a strongly typed way.

Here is the core TypeScript code

export class ListItemWrapper {
constructor(private listitem: SP.ListItem) {
}
public id(): number {
return this.listitem.get_id();
}

getOrSetAnyValue<T>(propertyname: string, value?: T): T {
if (!(typeof (value) === "undefined")) {
this.listitem.set_item(propertyname, value);
}
return this.listitem.get_item(propertyname);
}

public title(value?: string): string {
return this.getOrSetAnyValue("Title", value);
}

public _number(value?: number): number {
return this.getOrSetAnyValue("Number", value);
}
}

Here is how I am using the code.

Whenever I have a listitem, I am creating a wrapper.

var wrapper = new ListItemWrapper(listitem)

After that I can use properties of a wrapper either as wrapper.title() which basically returns the result, or like wrapper.title(“new string value”), which sets the result .

That’s all folks, this is easy and that is strongly typed! You have no misprints, and you have type checks.

You can download the whole demo solution from https://github.com/maratbakirov/SPTypeScriptExtraSamples which I plan to update. I will continue to upgrade the demo and I am planning to add a support for other types. Will start with Moment conversion as javascript default date formats are just weird. (Sorry americans, the default JavaScript format MM/DD/YYYY is considered weird in other countries including Russia and Australia Smile ). Also planning to try working with user and lookup fields.

About the author 

Marat Bakirov

Marat Bakirov is Senior Consultant Technical Specialist at ignia (ignia.com.au) and previously a Chief Solutions Architect for one of the leading Russian Sharepoint integrators. He has a large portfolio of many successful and diverse projects covering different aspects of Sharepoint including public sites, XSLT rendering, BCS programming and multi-language solutions.He has worked in 2007-2010 in Microsoft Russia as a Developer Evangelist. He is one of the organizers of the first and second Russia Sharepoint Conferences. He is also a 4 time Sharepoint MVP since Oct 2010 and a Software Developer since 1993.