Examples

This page contains some examples of how Typewriter can be used.

Model interfaces

This example creates typed model interfaces.

Models.tst

module Models { $Classes(*Model)[ 

    export interface $Name$TypeParameters { $Properties[
        $name: $Type;]
    }]
}
                        

Knockout models

This example creates typed models with recursive mapping from JSON objects for Knockout.js.

Models.tst

${
    using Typewriter.Extensions.Types;

    string KnockoutInitializer(Property property)
    {
        var type = property.Type;

        return type.IsEnumerable ?
            $"KnockoutObservableArray<{type.Name.TrimEnd('[', ']')}> = ko.observableArray<{type.Name.TrimEnd('[', ']')}>({type.Default()})" :
            $"KnockoutObservable<{type.Name}> = ko.observable<{type.Name}>({type.Default()})";
    }

    string TypeMap(Property property)
    {
        var type = property.Type;

        if (type.IsPrimitive)
        {
            return type.IsDate ?
                $"new Date(data.{property.name})" :
                $"data.{property.name}";
        }
        else
        {
            return type.IsEnumerable ?
                $"data.{property.name}.map(i => new {type.Name.TrimEnd('[', ']')}(i))" :
                $"new {type.Name}(data.{property.name})";
        }
    }
}
module App { $Classes(*Model)[

    export class $Name { 
        $Properties[
        public $name: $KnockoutInitializer;]

        constructor(data: any = null) {

            if (data !== null) { $Properties[
                this.$name($TypeMap);]
            }
        }
    }]
}
                        

Angular Web API Service

This example creates typed services for accessing ASP.NET Web API controllers for Angular.js.

ApiServices.tst

${
    using Typewriter.Extensions.WebApi;

    string ReturnType(Method m) => m.Type.Name == "IHttpActionResult" ? "void" : m.Type.Name;
    string ServiceName(Class c) => c.Name.Replace("Controller", "Service");
}
module App { $Classes(:ApiController)[

    export class $Name {

        constructor(private $http: ng.IHttpService) { 
        } $Methods[
        
        public $name = ($Parameters[$name: $Type][, ]) : ng.IHttpPromise<$ReturnType> => {
            
            return this.$http<$ReturnType>({
                url: `$Url`, 
                method: "$HttpMethod", 
                data: $RequestData
            });
        };]
    }
    
    angular.module("App").service("$ServiceName", ["$http", $Name]);]
}