Edit on GitHub

TypeScript Add ServiceStack Reference

ServiceStack and TypeScript Banner

ServiceStack’s Add ServiceStack Reference feature allows clients to generate Native Types from directly within VS.NET using ServiceStackVS VS.NET Extension - providing a simple way to give clients typed access to your ServiceStack Services.

First class development experience

TypeScript has become a core part of our overall recommended solution for Web Apps that’s integrated into all ServiceStackVS’s React and Aurelia Single Page App VS.NET Templates offering a seamless development experience with access to advanced ES6 features like modules, classes and arrow functions whilst still being able to target most web browsers with its down-level ES5 support. TypeScript also goes beyond ES6 with optional Type Annotations enabling better tooling support and compiler type feedback than what’s possible in vanilla ES6 - invaluable when scaling large JavaScript codebases.

We’re actively tracking TypeScript’s evolution and looking forward to integrating TypeScript 2.0 once it leaves beta.

Ideal Typed Message-based API

The TypeScript JsonServiceClient available in the servicestack-client npm package enables the same productive, typed API development experience available in our other 1st-class supported client platforms.

ServiceStack embeds additional type hints in each Request DTO in order to achieve the ideal typed, message-based API. You can see an example of this is below which shows how to create a C# Gist in Gislyn after adding a ServiceStack Reference to gistlyn.com and installing the servicestack-client npm package:

import { JsonServiceClient } from 'servicesack-client';
import { StoreGist, GithubFile } from './Gistlyn.dtos';

var client = new JsonServiceClient("http://gistlyn.com");

var request = new StoreGist();
var file = new GithubFile();
file.filename = "main.cs";
file.content = 'var greeting = "Hi, from TypeScript!";';
request.files = { [file.filename]: file };

    .then(r => { // r:StoreGistResponse
        console.log(`New C# Gist was created with id: ${r.gist}`);
        location.href = `http://gistlyn.com?gist=${r.gist}`;
    .catch(e => {
        console.log("Failed to create Gist: ", e.responseStatus);

Where the r param in the returned then() Promise callback is typed to StoreGistResponse DTO Type.

TypeScript ServiceClient

The servicestack-client is a clean “jQuery-free” implementation based on JavaScript’s new Fetch API standard, utilizing the isomorphic-fetch implementation so it can be used in both JavaScript client web apps as well as node.js server projects.


The easiest way to use TypeScript with ServiceStack is to start with one of ServiceStackVS TypeScript projects.

Other TypeScript or ES6 projects can install servicestack-client from npm with:

npm install --save servicestack-client

The Type Definitions are included in the above servicestack-client npm package, if using jspm they can be installed with:

npm install --save-dev servicestack-client

Enabling TypeScript async/await

To make API requests using TypeScript’s async/await feature you’ll need to create a TypeScript tsconfig.json config file that imports ES6 promises and W3C fetch definitions with:

  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [ "es2015", "dom" ]

The W3C fetch definitions are built into TypeScript 2.3+, if using older versions of TypeScript they can be installed with:

npm install --save-dev @types/whatwg-fetch

TypeScript Ambient Interface Definitions or Concrete Types

You can get both concrete types and interface definitions for your Services at the following routes:

Simple command-line utilities for TypeScript

The servicestack-cli npm package lets you quickly and easily Add and Update ServiceStack References via a simple typescript-ref command-line utility.


Prerequisites: Node.js (>=4.x, 6.x preferred), npm version 3+.

$ npm install -g servicestack-cli

Adding a ServiceStack Reference

To Add a TypeScript ServiceStack Reference just call typescript-ref with the URL of a remote ServiceStack instance:

$ typescript-ref http://techstacks.io


Saved to: techstacks.dtos.ts

Calling typescript-ref with just a URL will save the DTOs using the Host name, you can override this by specifying a FileName as the 2nd argument:

$ typescript-ref http://techstacks.io Tech


Saved to: Tech.dtos.ts

Updating a ServiceStack Reference

To Update an existing ServiceStack Reference, call typescript-ref with the Filename:

$ typescript-ref techstacks.dtos.ts


Updated: techstacks.dtos.ts

Which will update the File with the latest TypeScript Server DTOs from techstacks.io. You can also customize how DTOs are generated by uncommenting the TypeScript DTO Customization Options and updating them again.

Updating all TypeScript DTOs

Calling typescript-ref without any arguments will update all TypeScript DTOs in the current directory:

$ typescript-ref


Updated: Tech.dtos.ts
Updated: techstacks.dtos.ts

To make it more wrist-friendly you can also use the shorter ts-ref alias instead of typescript-ref.

Add TypeScript Reference

The easiest way to Add a ServiceStack Reference to your project is to right-click on a folder to bring up ServiceStackVS’s VS.NET context-menu item, then click on Add -> TypeScript Reference.... This opens a dialog where you can add the url of the ServiceStack instance you want to typed DTO’s for, as well as the name of the DTO source file that’s added to your project.

Add ServiceStack Reference

After clicking OK, the servers DTO’s are added to the project, yielding an instant typed API:

TypeScript native types

Update ServiceStack Reference

If your server has been updated and you want to update the client DTOs, simply right-click on the DTO file within VS.NET and select Update ServiceStack Reference for ServiceStackVS to download a fresh update.

TypeScript Reference Example

Lets walk through a simple example to see how we can use ServiceStack’s TypeScript DTO annotations in our JavaScript clients. Firstly we’ll need to add a TypeScript Reference to the remote ServiceStack Service by right-clicking on your project and clicking on Add > TypeScript Reference... (as seen in the above screenshot).

This will import the remote Services dtos into your local project which looks similar to:

/* Options:
Date: 2016-08-11 22:23:24
Version: 4.061
Tip: To override a DTO option, remove "//" prefix before updating
BaseUrl: http://techstacks.io

//MakePropertiesOptional: True
//AddServiceStackTypes: True
//AddResponseStatus: False
//AddDescriptionAsComments: True

// @Route("/technology/{Slug}")
export class GetTechnology implements IReturn<GetTechnologyResponse>
    Slug: string;
    createResponse() { return new GetTechnologyResponse(); }
    getTypeName() { return "GetTechnology"; }

export class GetTechnologyResponse
    Created: string;
    Technology: Technology;
    TechnologyStacks: TechnologyStack[];
    ResponseStatus: ResponseStatus;

In keeping with idiomatic style of local .ts sources, generated types are not wrapped within a module by default. This lets you reference the types you want directly using normal import destructuring syntax:

import { GetTechnology, GetTechnologyResponse } from './dtos';

Or import all Types into your preferred variable namespace with:

import * as dtos from './dtos';

const request = new dtos.GetTechnology();

Or if preferred, you can instead have the types declared in a module by specifying a GlobalNamespace:

/* Options:

GlobalNamespace: dtos

Looking at the types we’ll notice the DTO’s are plain TypeScript Types with any .NET attributes added in comments using AtScript’s proposed meta-data annotations format. This lets you view helpful documentation about your DTO’s like the different custom routes available for each Request DTO.

By default DTO properties are optional but can be made a required field by annotating the .NET property with the [Required] attribute or by uncommenting MakePropertiesOptional: False in the header comments which instead defaults to using required properties.

Properties always reflect to match the remote servers JSON Serialization configuration, i.e. will use camelCase properties when the AppHost is configured with:

JsConfig.EmitCamelCaseNames = true;

Making Typed API Requests

Making API Requests in TypeScript is the same as all other ServiceStack’s Service Clients by sending a populated Request DTO using a JsonServiceClient which returns typed Response DTO.

So the only things we need to make any API Request is the JsonServiceClient from the servicestack-client package and any DTO’s we’re using from generated TypeScript ServiceStack Reference, e.g:

import { JsonServiceClient } from 'servicestack-client';
import { GetTechnology } from './dtos';

const client = new JsonServiceClient("http://techstacks.io");

const request = new GetTechnology();
request.Slug = "ServiceStack";

    .then(r => {                  // typed to GetTechnologyResponse
        cont tech = r.Technology; // typed to Technology

        console.log(`${tech.Name} by ${tech.VendorName} (${tech.ProductUrl})`);
        console.log(`${tech.Name} TechStacks:`, r.TechnologyStacks);

Sending additional arguments with Typed API Requests

Many AutoQuery Services utilize implicit conventions to query fields that aren’t explicitly defined on AutoQuery Request DTOs, these can be queried by specifying additional arguments with the typed Request DTO, e.g:

const request = new FindTechStacks();

client.get(request, { VendorName: "ServiceStack" })
    .then(r => { })               // typed to QueryResponse<TechnologyStack> 

Making API Requests with URLs

In addition to making Typed API Requests you can also call Services using relative or absolute urls, e.g:



// http://techstacks.io/technology?Slug=ServiceStack
client.get<GetTechnologyResponse>("/technology", { Slug: "ServiceStack" }) 

DTO Customization Options

In most cases you’ll just use the generated TypeScript DTO’s as-is, however you can further customize how the DTO’s are generated by overriding the default options.

The header in the generated DTO’s show the different options TypeScript native types support with their defaults. Default values are shown with the comment prefix of //. To override a value, remove the // and specify the value to the right of the :. Any uncommented value will be sent to the server to override any server defaults.

The DTO comments allows for customizations for how DTOs are generated. The default options that were used to generate the DTO’s are repeated in the header comments of the generated DTOs, options that are preceded by a TypeScript comment // are defaults from the server, any uncommented value will be sent to the server to override any server defaults.

/* Options:
Date: 2015-11-21 00:32:00
Version: 4.048

GlobalNamespace: dtos
//MakePropertiesOptional: True
//AddServiceStackTypes: True
//AddResponseStatus: False

We’ll go through and cover each of the above options to see how they affect the generated DTO’s:

Change Default Server Configuration

The above defaults are also overridable on the ServiceStack Server by modifying the default config on the NativeTypesFeature Plugin, e.g:

//Server example in CSharp
var nativeTypes = this.GetPlugin<NativeTypesFeature>();
nativeTypes.MetadataTypesConfig.GlobalNamespace = "dtos";

We’ll go through and cover each of the above options to see how they affect the generated DTO’s:


Changes the name of the module that contain the generated TypeScript definitions:

declare module dtos


Changes whether types should be generated as ambient interface definitions or exported as concrete Types:

module dtos
    export interface IReturnVoid


Changes whether the default of whether each property is optional or not:

interface Answer
    AnswerId: number;
    Owner: User;
    IsAccepted: boolean;
    Score: number;
    LastActivityDate: number;
    LastEditDate: number;
    CreationDate: number;
    QuestionId: number;


Automatically add a ResponseStatus property on all Response DTO’s, regardless if it wasn’t already defined:

interface GetAnswers extends IReturn<GetAnswersResponse>
    ResponseStatus: ResponseStatus;


Lets you specify the Version number to be automatically populated in all Request DTO’s sent from the client:

interface GetAnswers extends IReturn<GetAnswersResponse>
    Version: number; //1

This lets you know what Version of the Service Contract that existing clients are using making it easy to implement ServiceStack’s recommended versioning strategy.

TypeScript Interface Definitions

By checking Only TypeScript Definitions check-box on the dialog when Adding a TypeScript Reference you can instead import Types as a TypeScript declaration file (.d.ts).

TypeScript declarations are just pure static type annotations, i.e. they don’t generate any code or otherwise have any effect on runtime behavior. This makes them useful as a non-invasive drop-in into existing JavaScript code where it’s just used to provide type annotations on existing JavaScript objects, letting you continue using your existing data types and ajax libraries.

Referencing TypeScript DTO’s

Once added to your project, use VS.NET’s JavaScript doc comments to reference the TypeScript definitions in your .ts scripts. The example below shows how to use the above TypeScript definitions to create a typed Request/Response utilizing jQuery’s Ajax API to fire off a new Ajax request on every keystroke:

/// <reference path="MyApis.dtos.d.ts"/>

<input type="text" id="txtHello" data-keyup="sayHello" /> 
<div id="result"></div>

    sayHello: function () {
        var request: dtos.Hello = {};
        request.title = "Dr";
        request.name = this.value;
        $.getJSON(createUrl("/hello", request), request, 
            function (r: dtos.HelloResponse) {

function createUrl(path: string, params: any): string {
    for (var key in params) {
        path += path.indexOf('?') < 0 ? "?" : "&";
        path += key + "=" + encodeURIComponent(params[key]);
    return path;

Here we’re just using a simple inline createUrl() function to show how we’re creating the url for the GET HTTP Request by appending all Request DTO properties in the QueryString, resulting in a HTTP GET Request that looks like:


There’s also a new $.ss.createUrl() API in ss-utils.js which also handles .NET Route definitions where it will populate any variables in the /path/{info} instead of adding them to the ?QueryString, e.g:

    sayHello: function () {
        var request: dtos.Hello = {};
        request.title = "Dr";
        request.name = this.value;
        $.getJSON($.ss.createUrl("/hello/{Name}", request), request, 
            function (r: dtos.HelloResponse) {

Which results in a HTTP GET request with the expected Url:


ServerEvents Client

The TypeScript ServerEventClient is an idiomatic port of ServiceStack’s C# Server Events Client in native TypeScript providing a productive client to consume ServiceStack’s real-time Server Events that can be used in both TypeScript Web and node.js server applications.

const channels = ["home"];
const client = new ServerEventsClient("/", channels, {
    handlers: {
        onConnect: (sub:ServerEventConnect) => {  // Successful SSE connection
            console.log("You've connected! welcome " + sub.displayName);
        onJoin: (msg:ServerEventJoin) => {        // User has joined subscribed channel
            console.log("Welcome, " + msg.displayName);
        onLeave: (msg:ServerEventLeave) => {      // User has left subscribed channel
            console.log(user.displayName + " has left the building");
        onUpdate: (msg:ServerEventUpdate) => {    // User's subscribed channels have changed
            console.log(user.displayName + " channels subscription were updated");
        onMessage: (msg:ServerEventMessage) => {} // Invoked for each other message
        //... Register custom handlers
        CustomMessage: (msg:CustomMessage) = {}   // Handle CustomMessage Request DTO
    receivers: { 
        //... Register any receivers
        tv: {
            watch: function (id) {                 // Handle 'tv.watch {url}' messages 
                var el = document.querySelector("#tv");
                if (id.indexOf('youtu.be') >= 0) {
                    var v = splitOnLast(id, '/')[1];
                    el.innerHTML = templates.youtube.replace("{id}", v);
                } else {
                    el.innerHTML = templates.generic.replace("{id}", id);
                el.style.display = 'block'; 
            off: function () {                     // Hanndle 'tv.off' messages
                var el = document.querySelector("#tv");
                el.style.display = 'none';
                el.innerHTML = '';

When publishing a DTO Type for your Server Events message, your clients will be able to benefit from the generated DTOs in TypeScript ServiceStack References.

ServiceStackIDEA plugin

ServiceStackIDEA is a plugin for JetBrains IntelliJ based IDEs to simplify development of client applications for ServiceStack services with integrated support for Add ServiceStack Reference feature.

ServiceStackIDEA now supports many of the most popular JetBrains IDEs including:

  • WebStorm, RubyMine, PhpStorm & PyCharm
    • TypeScript
  • IntelliJ
    • Java, Kotlin and TypeScript

TypeScript Support

By right clicking on any folder in your Project explorer, you can add a TypeScript reference by simply providing any based URL of your ServiceStack server.

Once this file as been added to your project, you can update your service DTOs by right clicking Update ServiceStack Reference or using the light bulb action (Alt+Enter by default).

This now means you can integrate with a ServiceStack service easily from your favorite JetBrains IDE when working with TypeScript!

Install ServiceStack IDEA from the Plugin repository

The ServiceStack IDEA is now available to install directly from within a supported IDE Plugins Repository, to Install Go to:

  1. File -> Settings... Main Menu Item
  2. Select Plugins on left menu then click Browse repositories… at bottom
  3. Search for ServiceStack and click Install plugin
  4. Restart to load the installed ServiceStack IDEA plugin