Function object

Topics: Language Specification
Oct 11, 2012 at 2:37 PM

function helloWorld(){
	return "hello";

helloWorld.message = "Greetings";

What is the equivalent of above valid JavaScript statement in TypeScript. Angular.js uses function object characteristics for specifying dependency injection (

Oct 11, 2012 at 7:37 PM
Edited Oct 11, 2012 at 7:40 PM

How about this:


interface IHasMessageToo {
	message : string;
	() : string;

declare var helloWorld : IHasMessageToo;

var helloWorld = function () {
	return "hello";

helloWorld.message = "Greetings";


I don't know if that's the shortest code to achieve it, but it generates the same output without a warning.  I couldn't find it in the spec or tutorials, but I pieced it together with the jQuery.d.ts example which must do this for the jQuery function.


Oct 11, 2012 at 10:54 PM
Edited Oct 11, 2012 at 10:58 PM

I use this pattern for AngularJS controllers:

interface HelloScope extends Scope {
    greeting: string;

class helloController {
    static $inject = ["$scope", "$location"];
    constructor($scope: HelloScope, $location: Location) {
        $scope.greeting = "Hello";

Also, take a look at for type declarations for AngularJS.

Jan 16, 2013 at 7:53 AM

Quite often the controllers are simple so everything is setup in a constructor. That means that there is one level of nesting that is not needed. That's why I often make controller only as a function. Then of course it is harder to specify dependencies, but this works now:


module UserSession {
    export interface Scope extends ng.Scope {

    export function Controller($scope: Scope,
                                          $log : ng.Log) {

        $scope.logout = function () {

    (<any>Controller).$inject = ['$scope', '$log'];