TypeScript 基本語法


TypeScript 基本語法

 

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 = 100;

String

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

Array

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

Enum

//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

//不確定類型,退出編譯檢查 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

//空白 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 = 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;//實現類無需實現 } 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()*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);

重載

//重載 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.泛型

基本語法

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 = 0; 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(3);//error loggingIdentity({length: 10, value: 3}); //只要類型包含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: 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 { } }

合並模塊和類

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 = 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM