3

I've got some JavaScript code that I'm trying to convert to Typescript.

Supposedly, typescript is a superset of JavaScript, except the following has compiler errors. Assuming I didn't import the ko library into typescript, how would I convert the following code:

(function(ko, viewModels){
    viewModels.MyViewModel = function(){
        //stuff in here
    }
}(ko, window.viewModels = window.viewModels || {}));

For references, this was my attempt in TypeScript

module viewModels {

    export class PartDetailsViewModel {
        public bar: string;
             constructor (){
                 this.bar = ko.foo(); //<-- compiler error, "ko" does not exist in current scope
             }
        }
    }
}
Fenton
  • 241,084
  • 71
  • 387
  • 401
Adam Tegen
  • 25,378
  • 33
  • 125
  • 153

1 Answers1

8

Look into TypeScript's "Ambient Declarations" which allow you to declare external members that will be supplied at run-time. So in your example, adding the following would make the compiler happy:

declare var ko;

By the way, I'd like to also direct you at this post: https://stackoverflow.com/a/12692174/806003

Sten provided a basic knockout interface so that you can specify a type on your declaration to get some static typing on it. Also found this in the comments: https://gist.github.com/3833509

Community
  • 1
  • 1
nxn
  • 3,975
  • 2
  • 20
  • 17
  • Better point to this KO declarations (as it is a bit more elaborated than the gist you pointing at) : https://github.com/sv01a/TypeScript-Knockoutjs – A. M. Oct 08 '12 at 13:43
  • 1
    Even more complete: https://github.com/borisyankov/DefinitelyTyped/blob/master/Definitions/knockout-2.2.d.ts – Markus Jarderot Nov 05 '12 at 18:55