Creating SharePoint solutions with TypeScript.

Abstract

This post explains how to use TypeScript in your apps for SharePoint. It assumes that you are familiar with SharePoint-hosted apps and JavaScript.

Great thanks for Jim Crowley from Microsoft to make the text awesome.

 

Introduction

SharePoint-hosted apps are written in JavaScript, which is often hard to debug. It also does not provide many of the advantages of a strongly typed language. Luckily, Anders Hejlsberg has created a superset of JavaScript called TypeScript. This language provides strong types, interfaces, and extensible classes that bring common object oriented programming concepts and techniques into JavaScript development.

The TypeScript compiler produces a JavaScript file from a source file with a .ts extension. You can think of TypeScript as your source code and JavaScript as analogous to binary code generated by a compiler.

The compiler also produces a map file that makes it possible for you to debug TypeScript code. This file maps lines of TypeScript with the lines of JavaScript produced by the compiler. The TypeScript debugger works as long as you include your TypeScript and map files in the same location as your JavaScript file.

You can easily install TypeScript as a plugin to your installation of Visual Studio 2012 and Visual Studio 2013 from the TypeScript official site (https://www.typescriptlang.org/).

 

Some JavaScript libraries, such as JQuery and the SharePoint JavaScript libraries, might be a little difficult to use with TypeScript. Since TypeScript is strongly typed, it will complain about the classes and functions in these libraries unless you have corresponding TypeScript definitions for them. The DefinitelyTyped project addresses this issue by putting a lot of these definitions on NuGet (https://github.com/borisyankov/DefinitelyTyped). You will find many libraries there, including ones for Knockout and JQuery. One library is called SharePoint.TypeScript.DefinitelyTyped. You can install it from NuGet, but you should also take a look at the project on CodePlex (https://sptypescript.codeplex.com), which contains samples for lots of common tasks, like CSR rendering, autofills, mQuery, forms with tabs, custom fields, search, user profiles, social capabilities, and more.

Using TypeScript in your project

It is very simple to include TypeScript in your SharePoint-hosted app project. Just follow these steps.

 

1. Install TypeScript to Visual Studio 2012 or Visual Studio 2013 from the official site.

2. Create a new Sharepoint-hosted app.

3. Now you need to do a little trick to make sure that Visual Studio knows how to compile TypeScript in the context of an app for SharePoint.

a. Right-click the project name and select Unload Project.

b. Right-click the project name and select Edit <your project name>.csproj.

c. Add these lines before the last closing <Project> tag.

 

<PropertyGroup>

    <TypeScriptSourceMap>true</TypeScriptSourceMap>

  </PropertyGroup>

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" />

1. Right-click the project name and select Reload Project.

2. Now you will see the TypeScript tab in the project properties.

4. Now you can add the TypeScript definitions. Right-click the project name and select Manage Nuget Packages. Search online for “sharePoint.Typescript.” Install the sharePoint.Typescript.DefinitelyTyped package.

5.

6. Also search for “jquery.typescript” and install the jquery.Typescript.DefinitelyTyped package.

7. Rename App.js to App_1.js so that we can use it later. Create a new TypeScript file called App.ts. You’ll need to search for the Typescript File type when you add this new item. Both of these files should be in the Scripts directory in Solution Explorer. You can also find this template in the Web category of templates.

8.

 

8. Copy the contents of App_1.js to App.ts.

9. Add these lines to the top of the App.ts file:

///<reference path="typings/sharepoint/SharePoint.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />

This will allow us to use both JQuery and SharePoint definitions.

10. Build the project.

11. In Solution Explorer press the Show all files button. The Scripts directory will include new App.js and App.js.map files. Right-click both file names and select Include In Project. Make sure that each file has a deployment type of ElementFile.

12. Now we have turned our Javascript Sharepoint-hosted app to a Typescript Sharepoint hosted app.

 

Adding the People Picker control with TypeScript

Now let’s see how to do a basic task. We’ll update an existing MSDN sample app (https://msdn.microsoft.com/en-us/library/jj713593.aspx) that adds a client-side People Picker control to an app for SharePoint so that it uses TypeScript. You can create this sample by updating the SharePoint-hosted app that we created in the last section.

 

1. Move these two lines from the App.ts file into the _references.js file in the Scripts directory:

///<reference path="typings/sharepoint/SharePoint.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />

2. Create a new web page inside the Pages directory of your project. Name it Default1.aspx.

3. Open the AppManifest.xml file and make this new page the Start page of your app. You’ll find this setting under the General tab.

4. Create a new TypeScript file inside the Scripts directory of your project. Name it App1.ts.

5. Build the project.

6. In Solution Explorer press the Show all files button. The Scripts directory will include new App1.js and App1.js.map files. Right-click both file names and select Include In Project. Make sure that each file has a deployment type of ElementFile.

7. Find this tag in your Default1.aspx file:

<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">

Copy this lines under that tag:

<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="../Scripts/App1.js"></script>
Note – the actual javascript version may differ on your computer, as the Nuget package always gets the latest jquery version.

8. Close the tag

</asp:Content>

9. Replace the contents of the PlaceHolderMain section with these lines:

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<SharePoint:ScriptLink name="clienttemplates.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="clientforms.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="clientpeoplepicker.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="autofill.js" runat="server" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink name="sp.js" runat="server" LoadAfterUI="true" Localizable="false" />

<SharePoint:ScriptLink runat="server" Name="mQuery.js" />
<div id="peoplePickerDiv"></div>

<div>
<br/>
<h1>User info:</h1>
<p id="resolvedUsers"></p>
<h1>User keys:</h1>
<p id="userKeys"></p>
</div>

</asp:Content>

Notice that we have added a reference to MQuery. MQuery is a JavaScript JQuery subset library built into SharePoint. It is more limited in scope than JQuery, but it contains the awesome m$.ready() function, which gives us a good entry point for our code after all of the SharePoint stuff has been loaded.

9. Add this TypeScript code to the App1.ts file:

 

module App1 {

    m$.ready(() => {

        loadPeoplePicker('peoplePickerDiv');

    });

 

    //Load the people picker

    function loadPeoplePicker(peoplePickerElementId: string) {

        var schema: ISPClientPeoplePickerSchema = {

            PrincipalAccountType: 'User,DL,SecGroup,SPGroup',

            SearchPrincipalSource: 15,

            ResolvePrincipalSource: 15,

    AllowMultipleValues: true,

            MaximumEntitySuggestions :50,

            Width: 280,

           

            OnUserResolvedClientScript: onUserResolvedClientScript

        }

 

        SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema);

    }

 

    function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) {

 

        var keys = "";

 

        // Get information about all users.

        var userInfo = '';

        for (var i = 0; i < users.length; i++) {

            var user = users[i];

            keys += user.Key + ",";

            for (var userProperty in user) {

                userInfo += userProperty + ': ' + user[userProperty] + '<br>';

            }

        }

        $('#resolvedUsers').html(userInfo);

 

        // Get user keys.

        $('#userKeys').html(keys);

 

    }

}

 

The code has the same length as in the MSDN article, but here we have a strongly typed schema for ClientPicker properties and we can easily add other properties. In the original JavaScript model, there is a dictionary, and you need to know the keys. Here we have strong type checking and IntelliSense, so the developer experience is dramatically better.

 

 

 

Press F5 to test your app. Here is what the app looks like when it runs.

 

 

 

Conclusion

 

You can find a more sophisticated sample at the SharePoint Typescript page on CodePlex (https://sptypescript.codeplex.com). This sample also gets data from user profile services. Here is what it looks like:

 

We strongly recommend that you also try this sample.

 

TypeScript is a very interesting and promising solution for using JavaScript with SharePoint. You can use Typescript in full trust solutions that include JavaScript.

 

You can find the source code for the solution used in this article on GitHub (https://github.com/maratbakirov/2013_12_OfficeBlogTypeScriptSample).