1. 类型
number
boolean
string
enum
Array<string>
any
void
var num:number = 10;
var str:string = "1231";
var bool:boolean = true;
var arr:number[] = [11,22,4,3];
function fun1(num:number): void{
num += 1;
}
var kkk:any = true;
enum color {red, wight, black};
console.log('enum: ', color[0]);
console.log('enum: ', color.red);
2. 类
2.1 属性、方法以及构造函数
class Person{
first_name:string;
second_name:string;
age:number;
constructor(fname?:string, sname?:string, age?:number){
this.first_name = fname;
this.second_name = sname;
this.age = age || 0;
}
AddInAge(addage:number):void{
this.age += addage;
}
}
var p:Person = new Person();// new Person('fname', 'sname', 10);
p.first_name = 'fname';
p.second_name = 'sname';
p.age = 10;
console.log(p);
p.AddInAge(5);
console.log(p);
2.2 继承
TypeScript强制执行的一条重要规则 : 派生类包含了一个构造函数,它必须调用 super(),它会执行基类的构造函数。 而且,在构造函数里访问 this的属性之前,我们 一定要调用 super()。
class Report{
data: Array<string>;
constructor(data:Array<string>){
this.data = data;
}
run(){
this.data.forEach(function(line){console.log(line)});
}
}
class TabbedReport extends Report{
headers: Array<string>;
constructor(headers:string[], values:string[]){
super(values);
this.headers = headers;
}
run(){
console.log(this.headers);
super.run();
}
}
var headers: string[] = ['Name'];
var data: string[] = ['Alice Green', 'Paul Pfifer', 'Louis Blakenship'];
var tab:TabbedReport = new TabbedReport(headers, data);
tab.run();
3. 工具
3.1 胖箭头函数语法
- 它和环绕它的外部代码共享同一个this
- 箭头函数是处理内联函数的好办法
var nate = {
name: "Nate",
guitars: ["Gibson", "Martin", "Taylor"],
printGuitars:function(){
var self = this;
this.guitars.forEach(function(g){
console.log(self.name, 'play ', g);
});
}
}
nate.printGuitars();
var nate = {
name: "Nate",
guitars: ["Gibson", "Martin", "Taylor"],
printGuitars:function(){
this.guitars.forEach(g=>{
console.log(this.name, 'play ', g); // 可以访问this
});
}
}
nate.printGuitars();
3.2 模板字符串 (反引号)
// (1) 字符串插值 可以在模板字符串中使用变量(不必被迫使用+来拼接字符串);
var dogname:string = 'dog';
console.log(`hello, ${dogname}`);
// (2) 支持多行字符串
var longstr: string = `
hello, dog;
hello, cat;
`
console.log(`longstr: ${longstr}`);