TypeScript 基本语法

TypeScript 是微软开发的 JavaScript 的超集,TypeScript 兼容 JavaScript,可以载入 JavaScript 代码然后运行。TypeScript 与 JavaScript 相比进步的地方 包括:加入注释,让编译器理解所支持的对象和函数,编译器会移除注释,不会增加开销;增加一个完整的类结构,使之更新是传统的面向对象语言。

TypeScript 微软官方网站 http://www.typescriptlang.org/
TypeScript 源码 http://typescript.codeplex.com

1. 基本数据类型

Boolean

1
2
//Boolean
var isDone:boolean = false;

Number

1
2
//Number
var width:number = 100;

String

1
2
//String
var name:string = "hello";

Array

1
2
3
//Array
var list:number[] = [1, 2, 3];
var list:Array<number>=[1, 2, 3];

Enum

1
2
3
4
5
6
7
8
9
10
11
12
//Enum
enum Color {Red, Green, Blue}
var c: Color = Color.Red;
alert(c);//默认值从0开始,alert(0);
//可以手动指定值
enum Color1 {Red = 1, Green, Blue}
var c1: Color1 = Color1.Green;
alert(c1);//alert(2)
//根据值查找名称
enum Color2 {Red = 1, Green=2, Blue=4}
var c2: string = Color2[4];
alert(c2);//alert(Blue)

Any

1
2
3
4
5
6
7
8
//不确定类型,退出编译检查
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

//不确定数组元素类型
var anylist:any[] = [1, true, "free"];
anylist[1] = 100;

Void

1
2
3
4
//空白
function warnUser(): void {
alert(123);
}

2. 类

基本语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Animal {
animalName:string;

constructor(name:string) {
this.animalName = name;
}

sayHello() {
alert(this.animalName + ": Hello");
}
}

var tom = new Animal("Tom");
tom.sayHello();//alert(Tom:Hello)

继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Animal {
animalName:string;

constructor(name:string) {
this.animalName = name;
}

sayHello() {
alert(this.animalName + ": Hello");
}
}

class Cat extends Animal {
//重写sayHello方法
sayHello() {
alert(this.animalName + "(Cat):" + "Hello");
}
}

class Mouse extends Animal {
sayHello() {
alert(this.animalName + "(Mouse):" + "Hello");
}
}

var tom:Animal = new Cat("Tom");
tom.sayHello();//alert(Tom(Cat):Hello)
var jerry:Animal = new Mouse("Jerry");
jerry.sayHello();//alert(Jerry(Mouse):Hello)

修饰符

当我们把 animalName 改为 private

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Animal {
private animalName:string;//默认是public

constructor(name:string) {
this.animalName = name;
}
//...
}

class Cat extends Animal {
//重写sayHello方法
sayHello() {
alert(this.animalName + "(Cat):" + "Hello");//Error 编译不通过
}
}

get,set 访问器

1
2
3
4
5
6
7
8
9
10
11
12
13
class Animal {
private _animalName:string;//默认是public

get animalName():string {
return this._animalName;
}

set animalName(name:string):string {
this._animalName = name;
}

//...
}

静态属性

1
2
3
4
5
6
7
8
//静态属性
class Table {
static width = 100;
static height = 200;
}

var width = Table.width;
alert(width);//alert(100)

3. 接口

基本语法

1
2
3
4
5
6
7
8
9
10
11
12
13
interface ICar {
color:string;
}

class Bus implements ICar {
color:string;
constructor() {
this.color = "Blue";
}
}

var bus = new Bus();
alert(bus.color);

继承接口

1
2
3
4
5
6
7
8
9
10
11
12
//继承接口
interface Shape {
color: string;
}

interface PenStroke {
penWidth: number;
}

interface Square extends Shape, PenStroke {
sideLength: number;
}

可选属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface ICar {
color:string;
safetyDevice?:any;//实现类无需实现
}

function MoveCar(car:ICar){
if(car.safetyDevice)
{
alert("The car is safe");
}
else
{
alert("The car is not safe");
}
}

4. 模块(Modules)

作用:1. 防止命名空间冲突;2. 将一个功能模块很容易的划分到不同文件中,更容易维护;

基本语法

1
2
3
4
5
6
7
8
9
module MyDemo {
export interface IDemo {

}

export class Demo implements IDemo {

}
}

别名

1
2
3
4
5
6
7
8
9
module Shapes {
export module Polygons {
export class Triangle { }
export class Square { }
}
}

import polygons = Shapes.Polygons;
var sq = new polygons.Square(); // 类似于 'new Shapes.Polygons.Square()'

5. 函数(Function)

基本语法

1
2
3
4
5
6
7
function add(x:number, y:number):number {
return x + y;
}
// or
var myAdd = function (x:number, y:number):number {
return x + y;
};

完整的函数类型

1
2
3
4
var myAdd:(x:number, y:number)=>number =
function (x:number, y:number):number {
return x + y;
};

为了增强可读性,给参数 x、y 具有实际的意义,可以这样写

1
2
3
4
var myAdd:(baseValue:number, increment:number)=>number =
function (x:number, y:number):number {
return x + y;
};

第二部分 number 是一个返回类型,如果无需返回类型,请使用’void’
第三部分的 function 参数类型,根据上下文类型进行推断,可以省略

1
2
3
4
var myAdd:(baseValue:number, increment:number)=>number =
function (x, y) {
return x + y;
};

可选参数

1
2
3
4
5
6
7
//可选参数
function buildName(firstName:string, lastName?:string) {
if (lastName)
return firstName + " " + lastName;
else return firstName;
}
var result1 = buildName("Bob");

默认参数

1
2
3
4
5
//默认参数
function buildNameDefaultValue(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}
var result1 = buildNameDefaultValue("Bob");

可变参数

例如在 C# 中,方法参数定义使用 param int[], 调用方法时,就可以传递多个 int 类型的参数
在 TypeScript 中

1
2
3
4
5
function buildNameRest(firstName:string, ...restOfName:string[]) {
return firstName + " " + restOfName.join(" ");
}

var employeeName = buildNameRest("Joseph", "Samuel", "Lucas", "MacKinzie")

Lambads 和 this 关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var people={
name:["张三","李四","王五","赵六"],
getName:function(){
return function(){
var i=Math.floor(Math.random()*4);
return {
n:this.name[i]
}
}
}
}

var pname=people.getName();
alert("名字:"+pname().n);

调用发现 getName 中的 this 关键字指向的是 getName, 访问不到外部的 name 属性
所以我们修改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var people = {
name: ["张三", "李四", "王五", "赵六"],
getName: function () {
return ()=> {
var i = Math.floor(Math.random() * 4);
return {
n: this.name[i]
}
}
}
}

var pname = people.getName();
alert("名字:" + pname().n);

重载

1
2
3
4
5
6
7
8
9
10
11
//重载
function student(name:string):string;
function student(age:number):number;
function student(numberorage:any):any {
if (numberorage && typeof (numberorage) == "string")
alert("姓名");
else
alert("年龄");
}
student("Tom");//alert("姓名")
student(15);//alert("年龄")

6. 泛型

基本语法

1
2
3
4
5
6
7
8
function identity<T>(arg: T): T {
return arg;
}

//数组泛型
function identity<T>(arg: T[]): T[] {
console.log(arg.length);
}

泛型类型(通用的函数类型)

1
2
3
4
5
6
function identity<T>(arg:T):T {
return arg;
}
var myIdentity:<T>(arg:T)=>T = identity;//T也可使用其他字母表示
//也可以这么写
//var myIdentity:{<T>(arg:T): T} = identity;

接口泛型

1
2
3
4
5
6
7
8
9
interface GenericIdentityFn {
<T>(arg:T): T;
}

function identity<T>(arg:T):T {
return arg;
}

var myIdentity:GenericIdentityFn = identity;

泛型类

1
2
3
4
5
6
7
8
9
10
class GenericNumber<T> {
zeroValue:T;
add:(x:T, y:T) => T;
}

var myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};

泛型约束

1
2
3
4
5
6
7
8
9
10
11
interface Lengthwise {
length: number;
}

function loggingIdentity<T extends Lengthwise>(arg:T):T {
console.log(arg.length);
return arg;
}

loggingIdentity(3);//error
loggingIdentity({length: 10, value: 3}); //只要类型包含length属性即可

泛型类约束

1
2
3
4
5
6
7
class Findable<T>
{
//...
}
function find<T>(n: T, s: Findable<T>) {
// ...
}

7. 合并

合并接口

1
2
3
4
5
6
7
8
9
10
interface Box {
height: number;
width: number;
}

interface Box {
scale: number;
}

var box: Box = {height: 5, width: 6, scale: 10};

合并模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module Animals {
exportclass Zebra { }
}

module Animals {
exportinterface Legged { numberOfLegs: number; }
exportclass Dog { }
}

//相当于
module Animals {
exportinterface Legged { numberOfLegs: number; }

exportclass Zebra { }
exportclass Dog { }
}

合并模块和类

1
2
3
4
5
6
7
class Album {
label:Album.AlbumLabel;
}
module Album {
export class AlbumLabel {
}
}

合并模块和函数

1
2
3
4
5
6
7
8
9
10
function buildLabel(name:string):string {
return buildLabel.prefix + name + buildLabel.suffix;
}

module buildLabel {
export var suffix = "";
export var prefix = "Hello, ";
}

alert(buildLabel("Sam Smith"));

合并模块与枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
enum Color {
red = 1,
green = 2,
blue = 4
}

module Color {
export function mixColor(colorName:string) {
if (colorName == "yellow") {
return Color.red + Color.green;
}
else if (colorName == "white") {
return Color.red + Color.green + Color.blue;
}
else if (colorName == "magenta") {
return Color.red + Color.blue;
}
else if (colorName == "cyan") {
return Color.green + Color.blue;
}
}
}

不能合并

  • 类与类不能合并
  • 接口与类不能合并
  • 变量与类不能合并

转载

转载请注明出处:http://www.cnblogs.com/xcong/p/4570235.html
文中代码引用自 Ts 官网和极客学院
TS 文件下载 http://files.cnblogs.com/files/xcong/TsDemo.zip