TypeScript 是微軟開發的 JavaScript 的超集,TypeScript兼容JavaScript,可以載入JavaScript代碼然後運行。TypeScript與JavaScript相比進步的地方 包括:加入注釋,讓編譯器理解所支持的對象和函數,編譯器會移除注釋,不會增加開銷;增加一個完整的類結構,使之更新是傳統的面向對象語言。
TypeScript 微軟官方網站 http://www.typescriptlang.org/
TypeScript 源碼 http://typescript.codeplex.com我用 TypeScript 語言的七個月 http://www.linuxidc.com/Linux/2013-07/87506.htm
//Boolean
var isDone:boolean = false;
//Number
var width:number = 100;
//String
var name:string = "hello";
//Array
var list:number[] = [1, 2, 3];
var list:Array<number>=[1, 2, 3];
//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)
//不確定類型,退出編譯檢查
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
//不確定數組元素類型
var anylist:any[] = [1, true, "free"];
anylist[1] = 100;
//空白
function warnUser(): void {
alert(123);
}
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 編譯不通過
}
}
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)
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");
}
}
作用: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()'
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")
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("年齡")
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>) {
// ...
}
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;
}
}
}