标签:
string:
function greeter(person: string) { return "Hello, " + person; } var user = "Jane User"; document.body.innerHTML = greeter(user);
Array:
function greeter(person: string) { return "Hello, " + person; } var user = [0, 1, 2]; document.body.innerHTML = greeter("C" + user[0]);
interface(感觉和结构体很像,注意它是变量名称放在前面,类型放在后面):
interface Person { firstname: string; lastname: string; } function greeter(person: Person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = { firstname: "Jane", lastname: "User" }; document.body.innerHTML = greeter(user);
class, 里面的构造器和公共成员变量有些特别(跟C#的写法不一样),类没有作用域区分,会检查成员变量作用域,希望以后的版本能完善,接口还能parse这些class, 还不知道接口能不能定义方法。
class Student { fullname : string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + middleinitial + " " + lastname; } } interface Person { firstname: string; lastname: string;
} function greeter(person : Person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);
我们来看一下它生成的JavaScript代码, 实例化的Student调用了一个闭包函数并将成员变量转换成Student的node就变成了这样一个链条变量,没有作用域哦,其他的都在typescript里面帮我们写好,就像一个模板一样,可以写一些更抽象的东西(比如说链表,还没测试这个会生成什么样子)。Map这个文件可能是给调试用的:
var Student = (function () { function Student(firstname, middleinitial, lastname) { this.firstname = firstname; this.middleinitial = middleinitial; this.lastname = lastname; this.fullname = firstname + " " + middleinitial + " " + lastname; } return Student; })(); function greeter(person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user); //# sourceMappingURL=greeter.js.map
{"version":3,"file":"greeter.js","sourceRoot":"","sources":["greeter.ts"],"names":["Student","Student.constructor","greeter"],"mappings":"AAAA;IAEIA,iBAAmBA,SAASA,EAAUA,aAAaA,EAAUA,QAAQA;QAAlDC,cAASA,GAATA,SAASA,CAAAA;QAAUA,kBAAaA,GAAbA,aAAaA,CAAAA;QAAUA,aAAQA,GAARA,QAAQA,CAAAA;QACjEA,IAAIA,CAACA,QAAQA,GAAGA,SAASA,GAAGA,GAAGA,GAAGA,aAAaA,GAAGA,GAAGA,GAAGA,QAAQA,CAACA;IACrEA,CAACA;IACLD,cAACA;AAADA,CAACA,AALD,IAKC;AAOD,iBAAiB,MAAe;IAC5BE,MAAMA,CAACA,SAASA,GAAGA,MAAMA,CAACA,SAASA,GAAGA,GAAGA,GAAGA,MAAMA,CAACA,QAAQA,CAACA;AAChEA,CAACA;AAED,IAAI,IAAI,GAAG,IAAI,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAE7C,QAAQ,CAAC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC"}
标签:
原文地址:http://www.cnblogs.com/ByronWu12345/p/4794036.html