Skip to content

TypeScript Add ServiceStack Reference

Demis Bellot edited this page Oct 25, 2016 · 12 revisions

This page has moved to

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 and installing the servicestack-client npm package:

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

var client = new JsonServiceClient("");

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 = `${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.

Isomorphic Fetch

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 with:

jspm install servicestack-client

and node server projects can instead install it with:

npm install servicestack-client --save

Then fetch the Type Definitions for either project type with:

typings install servicestack-client --save
typings install dt~isomorphic-fetch --global --save

TypeScript Ambient Interface Definitions or Concrete Types

Use the ExportAsTypes=true option to generate non-ambient concrete TypeScript Types. This option is enabled at the new /types/typescript route so you can get both concrete types and interface definitions at:

Add ServiceStack 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

//ExportAsTypes: True
//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("");

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);

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
//ExportAsTypes: False
//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"; = 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"; = this.value;
        $.getJSON($.ss.createUrl("/hello/{Name}", request), request, 
            function (r: dtos.HelloResponse) {

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



In addition to JsonServiceClient most of the JavaScript utils in ss-utils.js are also in the servicestack-client npm package including the ServerEventsClient for processing real-time Server Events.

Here's how Gistlyn uses ServerEventsClient for handling real-time Script Status updates and Console logs from the executing C# Script:

const channels = ["gist"];
const sse = new ServerEventsClient("/", channels, {
    handlers: {
        onConnect(activeSub:ISseConnect) {                       // Successful SSE connection
            store.dispatch({ type: 'SSE_CONNECT', activeSub });  // Tell Redux Store we're connected 
            fetch("/session-to-token", {                         // Convert Session to JWT
                method:"POST", credentials:"include" 
        ConsoleMessage(m, e) {                                   // C# Gist Console Logs
            batchLogs.queue({ msg: m.message });
        ScriptExecutionResult(m:ScriptExecutionResult, e) {      // Script Status Updates

If you're publishing a DTO Type for your Server Events message you'll also be able to benefit from the generated Type definition like Gistlyn does with ScriptExecutionResult.

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

  1. Getting Started

    1. Creating your first project
    2. Create Service from scratch
    3. Your first webservice explained
    4. Example Projects Overview
    5. Learning Resources
  2. Designing APIs

    1. ServiceStack API Design
    2. Designing a REST-ful service with ServiceStack
    3. Simple Customer REST Example
    4. How to design a Message-Based API
    5. Software complexity and role of DTOs
  3. Reference

    1. Order of Operations
    2. The IoC container
    3. Configuration and AppSettings
    4. Metadata page
    5. Rest, SOAP & default endpoints
    6. SOAP support
    7. Routing
    8. Service return types
    9. Customize HTTP Responses
    10. Customize JSON Responses
    11. Plugins
    12. Validation
    13. Error Handling
    14. Security
    15. Debugging
    16. JavaScript Client Library (ss-utils.js)
  4. Clients

    1. Overview
    2. C#/.NET client
      1. .NET Core Clients
    3. Add ServiceStack Reference
      1. C# Add Reference
      2. F# Add Reference
      3. VB.NET Add Reference
      4. Swift Add Reference
      5. Java Add Reference
    4. Silverlight client
    5. JavaScript client
      1. Add TypeScript Reference
    6. Dart Client
    7. MQ Clients
  5. Formats

    1. Overview
    2. JSON/JSV and XML
    3. HTML5 Report Format
    4. CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  6. View Engines 4. Razor & Markdown Razor

    1. Markdown Razor
  7. Hosts

    1. IIS
    2. Self-hosting
    3. Messaging
    4. Mono
  8. Security

    1. Authentication
    2. Sessions
    3. Restricting Services
    4. Encrypted Messaging
  9. Advanced

    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in profiling
    9. Form Hijacking Prevention
    10. Auto-Mapping
    11. HTTP Utils
    12. Dump Utils
    13. Virtual File System
    14. Config API
    15. Physical Project Structure
    16. Modularizing Services
    17. MVC Integration
    18. ServiceStack Integration
    19. Embedded Native Desktop Apps
    20. Auto Batched Requests
    21. Versioning
    22. Multitenancy
  10. Caching

  11. Caching Providers

  12. HTTP Caching 1. CacheResponse Attribute 2. Cache Aware Clients

  13. Auto Query

  14. Overview

  15. Why Not OData

  16. AutoQuery RDBMS

  17. AutoQuery Data 1. AutoQuery Memory 2. AutoQuery Service 3. AutoQuery DynamoDB

  18. Server Events

    1. Overview
    2. JavaScript Client
    3. C# Server Events Client
    4. Redis Server Events
  19. Service Gateway

    1. Overview
    2. Service Discovery
  20. Encrypted Messaging

    1. Overview
    2. Encrypted Client
  21. Plugins

    1. Auto Query
    2. Server Sent Events
    3. Swagger API
    4. Postman
    5. Request logger
    6. Sitemaps
    7. Cancellable Requests
    8. CorsFeature
  22. Tests

    1. Testing
    2. HowTo write unit/integration tests
  23. ServiceStackVS

    1. Install ServiceStackVS
    2. Add ServiceStack Reference
    3. TypeScript React Template
    4. React, Redux Chat App
    5. AngularJS App Template
    6. React Desktop Apps
  24. Other Languages

    1. FSharp
      1. Add ServiceStack Reference
    2. VB.NET
      1. Add ServiceStack Reference
    3. Swift
    4. Swift Add Reference
    5. Java
      1. Add ServiceStack Reference
      2. Android Studio & IntelliJ
      3. Eclipse
  25. Amazon Web Services

  26. ServiceStack.Aws

  27. PocoDynamo

  28. AWS Live Demos

  29. Getting Started with AWS

  30. Deployment

    1. Deploy Multiple Sites to single AWS Instance
      1. Simple Deployments to AWS with WebDeploy
    2. Advanced Deployments with OctopusDeploy
  31. Install 3rd Party Products

    1. Redis on Windows
    2. RabbitMQ on Windows
  32. Use Cases

    1. Single Page Apps
    2. HTML, CSS and JS Minifiers
    3. Azure
    4. Connecting to Azure Redis via SSL
    5. Logging
    6. Bundling and Minification
    7. NHibernate
  33. Performance

    1. Real world performance
  34. Other Products

    1. ServiceStack.Redis
    2. ServiceStack.OrmLite
    3. ServiceStack.Text
  35. Future

    1. Roadmap
Clone this wiki locally
You can’t perform that action at this time.