将类从javascript转换为typescript

时间:2015-12-11 01:41:01

标签: javascript angularjs typescript

我想知道如何将以下代码段转换为Typescript。我正在学习Angular2并且对打字稿很新。

在JS中,我们可以有这样的生活(我只是在脑海中随意思考,并使用下面的代码片段来表达我的想法)

(function(){
record.question = function(){
    var charLength = 1,
        author = "",
        foo = fooWoo
        voteCount= 0;

    function question(g){
        //do something, oh yeah!
    }

    question.foo = function(x){
        foo = x;
        return question;
    }

    question.charLength = function(x){
        //do some setup
        return question;
    }

    question.author = function(x){
        //give me the name of author
        return author;
    }

    question.voteCount = function(x){
        //retrieve vote count
        return voteCount;
    }

    return question;
};

function fooWoo(d){

}
})();

然后在我的其他js文件中,我可以直接使用这样的东西:

var q = record.question();

我怎么能在打字稿中写这个?有任何想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

有时,在新语法中查看熟悉的内容有助于理解。所以这就是或多或少的样子

class Question {
  private charLength:number = 1;
  private author:string = "";
  private foo:FooWoo;

  constructor(
    private fp : FooWoo,
    private g:any ){
    //give me the name of author
    }    

  foo(x){
    this.foo = x;
    return this;
  }

  charLength(x){
    //do some setup
    return this;
  }

  author(x){
    //give me the name of author
    return this.author;
  }

  voteCount(x){
    //retrieve vote count
    return this.voteCount;
  }
}

然后你会像这样实例化这个类:

var q = new Question(new FooWoo(), "whatever g is");

iife通常由typescript编译器或您正在使用的任何机箱库处理。