Skip to content

How to use TypeScript for making strongly typed data in SharePoint hosted apps?

October 25, 2013

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. 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!

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.

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: