TypeScript 基本文法
1.基礎資料型別 (Elementary Data Type)x
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"); }}
2.類基本文法x
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"); }}
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;}// orvar 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("年齡")5.泛型基本文法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);//errorloggingIdentity({length: 10, value: 3}); //只要類型包含length屬性即可泛型類約束class Findable<T>{ //...}function find<T>(n: T, s: Findable<T>) { // ...}
6.合并合并介面
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; } }}
不能合并類與類不能合并介面與類不能合并變數與類不能合并