TypeScript 基本语法

TypeScript 是微软开发的 JavaScript 的超集,TypeScript兼容JavaScript,可以载入JavaScript代码然后运行。TypeScript与JavaScript相比进步的地方 包括:加入注释,让编译器理解所支持的对象和函数,编译器会移除注释,不会增加开销;增加一个完整的类结构,使之更新是传统的面向对象语言。
TypeScript 微软官方网站 http://www.typescriptlang.org/
TypeScript 源码 http://typescript.codeplex.com
1.基本数据类型
Boolean
//Booleanvar isDone:boolean = false;
Number
//Numbervar width:number = 100;
String
//Stringvar name:string = "hello";
Array
//Arrayvar list:number[] = [1, 2, 3];
var list:Array=[1, 2, 3];
Enum
//EnumenumColor{Red, Green, Blue}
varc: Color = Color.Red;
alert(c);//默认值从0开始,alert(0);//可以手动指定值enumColor1{Red = 1, Green, Blue}
var c1: Color1 = Color1.Green;
alert(c1);//alert(2)//根据值查找名称enumColor2{Red = 1, Green=2, Blue=4}
var c2: string = Color2[4];
alert(c2);//alert(Blue)
Any
//不确定类型,退出编译检查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
//空白functionwarnUser(): void {

alert(123);

}
2.类
基本语法
classAnimal{

animalName:string;

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

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

}

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

animalName:string;

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

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

}

classCatextendsAnimal{

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

}

classMouseextendsAnimal{

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

}

var tom:Animal = newCat("Tom");
tom.sayHello();//alert(Tom(Cat):Hello)var jerry:Animal = newMouse("Jerry");
jerry.sayHello();//alert(Jerry(Mouse):Hello)
修饰符
当我们把animalName 改为private
classAnimal{

private animalName:string;//默认是public

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

}

classCatextendsAnimal{

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

}
get,set 访问器
classAnimal {

private _animalName:string;//默认是publicgetanimalName():string{
    returnthis._animalName;
}

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

//...

}
静态属性
//静态属性classTable{

static width = 100;
static height = 200;

}

var width = Table.width;
alert(width);//alert(100)
3.接口
基本语法
interface ICar {

color:string;

}

class Bus implements ICar {

color:string;
constructor() {
    this.color = "Blue";
}

}

var bus = new Bus();
alert(bus.color);
继承接口
//继承接口interface Shape {

color: string;

}

interface PenStroke {

penWidth: number;

}

interface Square extends Shape, PenStroke {

sideLength: number;

}
可选属性
interface ICar {

color:string;
safetyDevice?:any;//实现类无需实现

}

functionMoveCar(car:ICar){

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

}
4.模块(Modules)
作用:1.防止命名空间冲突;2.将一个功能模块很容易的划分到不同文件中,更容易维护;
基本语法
module MyDemo {

exportinterface IDemo {

}

exportclass Demo implements IDemo {

}

}
别名
module Shapes {

exportmodule Polygons {
    exportclassTriangle{ }
    exportclassSquare{ }
}

}

import polygons = Shapes.Polygons;
var sq = new polygons.Square(); // 类似于 'new Shapes.Polygons.Square()'
5.函数(Function)
基本语法
function add(x:number, y:number):number {

return x + y;

}
// or
var myAdd = function (x:number, y:number):number {

return x + y;

};
完整的函数类型
var myAdd:(x:number, y:number)=>number =

function (x:number, y:number):number {
    return x + y;
};

为了增强可读性,给参数x、y具有实际的意义,可以这样写
var myAdd:(baseValue:number, increment:number)=>number =

function (x:number, y:number):number {
    return x + y;
};

第二部分number 是一个返回类型,如果无需返回类型,请使用 'void'
第三部分的function 参数类型,根据上下文类型进行推断,可以省略
var myAdd:(baseValue:number, increment:number)=>number =

function (x, y) {
    return x + y;
};

可选参数
//可选参数functionbuildName(firstName:string, lastName?:string) {

if (lastName)
    return firstName + " " + lastName;
elsereturn firstName;

}
var result1 = buildName("Bob");
默认参数
//默认参数functionbuildNameDefaultValue(firstName: string, lastName = "Smith"){

    return firstName + " " + lastName;

}
var result1 = buildNameDefaultValue("Bob");
可变参数
例如在C#中,方法参数定义使用param int[],调用方法时,就可以传递多个int类型的参数
在TypeScript中
function buildNameRest(firstName:string, ...restOfName:string[]) {

return firstName + " " + restOfName.join(" ");

}

var employeeName = buildNameRest("Joseph", "Samuel", "Lucas", "MacKinzie")
Lambads 和this关键字
var people={

name:["张三","李四","王五","赵六"],
getName:function(){
    returnfunction(){
        var i=Math.floor(Math.random()*4);
        return {
            n:this.name[i]
        }
    }
}

}

var pname=people.getName();
alert("名字:"+pname().n);
调用发现getName中的this关键字指向的是getName,访问不到外部的name属性
所以我们修改为:
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);
重载
//重载functionstudent(name:string):string;
functionstudent(age:number):number;
functionstudent(numberorage:any):any{

if (numberorage && typeof (numberorage) == "string")
    alert("姓名");
else
    alert("年龄");

}
student("Tom");//alert("姓名")
student(15);//alert("年龄")
6.泛型
基本语法
function identity(arg: T): T {

return arg;

}

//数组泛型
function identity(arg: T[]): T[] {

console.log(arg.length);

}
泛型类型(通用的函数类型)
function identity(arg:T):T {

return arg;

}
var myIdentity:(arg:T)=>T = identity;//T也可使用其他字母表示
//也可以这么写
//var myIdentity:{(arg:T): T} = identity;
接口泛型
interface GenericIdentityFn {

<T>(arg:T): T;

}

function identity(arg:T):T {

return arg;

}

var myIdentity:GenericIdentityFn = identity;
泛型类
classGenericNumber {

zeroValue:T;
add:(x:T, y:T) => T;

}

var myGenericNumber = new GenericNumber();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y){

return x + y;

};
泛型约束
interface Lengthwise {

length: number;

}

functionloggingIdentity(arg:T):T{

console.log(arg.length);
return arg;

}

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

//...

}
functionfind(n: T, s: Findable) {

// ...

}
7.合并
合并接口
interface Box {

height: number;
width: number;

}

interface Box {

scale: number;

}

var box: Box = {height: 5, width: 6, scale: 10};
合并模块
module Animals {

exportclass Zebra { }

}

module Animals {

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

}

//相当于
module Animals {

exportinterface Legged { numberOfLegs: number; }

exportclass Zebra { }
exportclass Dog { }

}
合并模块和类
classAlbum{

label:Album.AlbumLabel;

}
module Album {

exportclassAlbumLabel{
}

}
合并模块和函数
functionbuildLabel(name:string):string{

return buildLabel.prefix + name + buildLabel.suffix;

}

module buildLabel {

exportvar suffix = "";
exportvar prefix = "Hello, ";

}

alert(buildLabel("Sam Smith"));
合并模块与枚举
enum Color {

red = 1,
green = 2,
blue = 4

}

module Color {

exportfunctionmixColor(colorName:string) {
    if (colorName == "yellow") {
        return Color.red + Color.green;
    }
    elseif (colorName == "white") {
        return Color.red + Color.green + Color.blue;
    }
    elseif (colorName == "magenta") {
        return Color.red + Color.blue;
    }
    elseif (colorName == "cyan") {
        return Color.green + Color.blue;
    }
}

}
不能合并
类与类不能合并
接口与类不能合并
变量与类不能合并
转载请注明出处:http://www.cnblogs.com/xcong/p/4570235.html

标签: none

评论已关闭