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
             }
        }
    }
}

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Better point to this KO declarations (as it is a bit more elaborated than the gist you pointing at) : github.com/sv01a/TypeScript-Knockoutjs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.