天天看點

TypeScript 基本文法 1.基本資料類型 2.類 3.接口 4.子產品(Modules) 5.函數(Function) 6.泛型 7.合并

TypeScript 是微軟開發的 JavaScript 的超集,TypeScript相容JavaScript,可以載入JavaScript代碼然後運作。TypeScript與JavaScript相比進步的地方 包括:加入注釋,讓編譯器了解所支援的對象和函數,編譯器會移除注釋,不會增加開銷;增加一個完整的類結構,使之更新是傳統的面向對象語言。

TypeScript 微軟官方網站 http://www.typescriptlang.org/

TypeScript 源碼 http://typescript.codeplex.com

1.基本資料類型

Boolean

//Boolean
var isDone:boolean = false;
           

Number

//Number
var width:number = ;
           

String

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

Array

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

Enum

//Enum
enum Color {Red, Green, Blue}
var c: Color = Color.Red;
alert(c);//預設值從0開始,alert(0);
//可以手動指定值
enum Color1 {Red = , Green, Blue}
var c1: Color1 = Color1.Green;
alert(c1);//alert(2)
//根據值查找名稱
enum Color2 {Red = , Green=, Blue=}
var c2: string = Color2[];
alert(c2);//alert(Blue)
           

Any

//不确定類型,退出編譯檢查
var notSure: any = ;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

//不确定數組元素類型
var anylist:any[] = [, true, "free"];
anylist[] = ;
           

Void

//空白
function warnUser(): void {
    alert(123);
}
           

2.類

基本文法

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)
           

繼承

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

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 通路器

class Animal {
    private _animalName:string;//預設是public

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

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

    //...
}
           

靜态屬性

//靜态屬性
class Table {
    static width = ;
    static height = ;
}

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;//實作類無需實作
}

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

4.子產品(Modules)

作用:1.防止命名空間沖突;2.将一個功能子產品很容易的劃分到不同檔案中,更容易維護;

基本文法

module MyDemo {
    export interface IDemo {

    }

    export class Demo implements IDemo {

    }
}
           

别名

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)

基本文法

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;
    };
           

可選參數

//可選參數
function buildName(firstName:string, lastName?:string) {
    if (lastName)
        return firstName + " " + lastName;
    else return firstName;
}
var result1 = buildName("Bob");
           

預設參數

//預設參數
function buildNameDefaultValue(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(){
        return function(){
            var i=Math.floor(Math.random()*);
            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() * );
            return {
                n: this.name[i]
            }
        }
    }
}

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

重載

//重載
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();//alert("年齡")
           

6.泛型

基本文法

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

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

泛型類型(通用的函數類型)

function identity<T>(arg:T):T {
    return arg;
}
var myIdentity:<T>(arg:T)=>T = identity;//T也可使用其他字母表示
//也可以這麼寫
//var myIdentity:{<T>(arg:T): T} = identity;
           

接口泛型

interface GenericIdentityFn {
    <T>(arg:T): T;
}

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

var myIdentity:GenericIdentityFn = identity;
           

泛型類

class GenericNumber<T> {
    zeroValue:T;
    add:(x:T, y:T) => T;
}

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

泛型限制

interface Lengthwise {
    length: number;
}

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

loggingIdentity();//error
loggingIdentity({length: , value: });  //隻要類型包含length屬性即可
           

泛型類限制

class Findable<T>
{
    //...
}
function find<T>(n: T, s: Findable<T>) {
    // ...
}
           

7.合并

合并接口

interface Box {
    height: number;
    width: number;
}

interface Box {
    scale: number;
}

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

合并子產品

module Animals {
    exportclass Zebra { }
}

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

//相當于
module Animals {
    exportinterface Legged { numberOfLegs: number; }
    
    exportclass Zebra { }
    exportclass Dog { }
}
           

合并子產品和類

class Album {
    label:Album.AlbumLabel;
}
module Album {
    export class AlbumLabel {
    }
}
           

合并子產品和函數

function buildLabel(name:string):string {
    return buildLabel.prefix + name + buildLabel.suffix;
}

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

alert(buildLabel("Sam Smith"));
           

合并子產品與枚舉

enum Color {
    red = ,
    green = ,
    blue = 
}

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

繼續閱讀