typeScript 是一種給 JavaScript 添加特性的語言擴展。如:類型批註和編譯時類型檢查、類、接口、模塊。javascript
數據類型系統: numbers, strings, structures, boolean等,當類型沒有給出時,TypeScript 編譯器利用類型推斷以推斷類型。若是因爲缺少聲明,沒有類型能夠被推斷出,那麼它就會默認爲是動態的 any 類型。any’類型是一種強大的兼容存在的 JavaScript 庫的類型系統。他容許跳過 TypeScript 的編譯時類型的檢查。(這些值可能來自動態內容,例如從用戶或第三方庫。在這種狀況下,咱們要退出類型檢查)html
any:前端
var notSure: any = 4;//notSure 這個是不肯定的值,默認先給一個數字 4java
notSure = "this string";//改變這個值爲 this stringjquery
notSure = false; //最終肯定的值是一個 boolean 值.typescript
數組 Array:
//第一種方式,你能夠在數據類型以後帶上’[]‘:
var list:number[] = [1, 2, 3];
//第二種方式,也能夠採用泛型的數組類型:
var list1:Array<number> = [1, 2, 3];//泛型數組數組
var isFlag:boolean=false;這個 : 號表明應該是表明繼承的意思瀏覽器
枚舉 Enum
enum Color {Red, Green, Blue};//enum 關鍵字 枚舉對象{聲明變量}
var c1: Color = Color.Green;//從枚舉裏面拿出綠色出來賦給一個叫 c 的變量
//---------手動枚舉全部值都設置---------------------
//默認枚舉類型其實數值從 0 開始,你能夠可用手動設置某一個成員的數值。例如咱們能夠將上文
的起始值定爲 1:
enum Color1 {Red = 1, Green = 2, Blue = 4};
var c2: Color1 = Color1.Green;
//---------手動設置所有的枚舉成員:---------------------
enum Color2 {Red = 1, Green, Blue};
var colorName: string = Color2[2];curl
var Color1;
(function (Color1) {
Color1[Color1["Red"] = 1] = "Red";
Color1[Color1["Green"] = 2] = "Green";
Color1[Color1["Blue"] = 4] = "Blue";
})(Color1 || (Color1 = {}));ide
void 和‘any’相對的數據類型則是’Void‘,它表明沒有任何數據類型。咱們經常使用的一個方法
沒有任何返回值:
//,格式如:function doMain:void{}
function warnUser(): void {
alert("This is my void");
}
例子:ts & js
/***返回 string 一個值***/
function setTableRowHtml2():string{
var userName:string="";
$("tr").each(function(){
userName=$(this).find("td:eq(1)").html();
);
return userName;
}
Ts 編譯生成的 js
/***返回 string 一個值***/
function setTableRowHtml2() {
var userName = "";
$("tr").each(function () {
userName = $(this).find("td:eq(1)").html();
});
return userName;
}
TypeScript 接口
/**--聲明一個接口,這個接口不會在 js 上面出現,只會在顯示一個 user 對象在 getUserInfo*/
interface IUserInfo{
age : any;//定義一個任何變量的 age.
userName :string;//定義一個 username.
}
/*********獲取用戶信息*******/
function getUserInfo(user : IUserInfo):string{
return user.age+"======"+user.userName;
}
//用一個數組對象做爲一個 user 對象傳值過 getUserInfo 函數方法..參數必需要以接口
IUserInfo 對應上.
少傳一個參數,typescript 會自動幫你檢測報錯,若是用純 javascript 去寫的話,不會報錯,
ts 大大減小檢查 js 問題
interface SquareConfig {
color?: string;//
width?: number;
}
/***************建立一個對象 function.**************/
function createSquare(config: SquareConfig): {color: string; area: number} {
//此時 newSquare 裏面的參數必須與 :後面裏面的參數名稱一致.
var newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = newSquare.area * config.width;
}
return newSquare;
}
//--createSquare 返回的對象是 newSquare,全部只能獲取 color 和 area 並獲取不了 width
這個屬性的值..
var mySquare1 = createSquare({color: "red"});//與接口的變量 color 同樣,此時這個值
是取出是默認值 color=red
var mySquare2 = createSquare({color1: "red"});//與接口的變量 color 不同,此時這
個值是取出是默認值 color=white
console.log(mySquare1.color+"=="+mySquare1.area);//
console.log(mySquare2.color+"=="+mySquare2.area);//
var mySquare3 = createSquare({color: "yellow",width:80});//這裏給了兩個變量值,
一個是 color,一個是 width
console.log(mySquare3.color+"=="+mySquare3.area);//因此這個值必須等於 800JavaScript 的 的 search 函數//--typescript 的 function 類型結合 javascript 的 search 函數使interface searchFunt{
//聲明一個兩個變量..
(source: string, subString: string): boolean;
}
var mySearch : searchFunt;//聲明一個 interface 變量接收
mySearch = function(source:string,subString:string){
var result = source.search(subString);
if (result == -1) {
return false;
}
else {
return true;
}
}
$(function(){
var source:string ="this is ok";
var subString1:string ="ok";
var subString2:string ="not";
var result:boolean;
var result1= mySearch(source,subString1);//從 source 字符串上面找 ok,返回值
是 true
var result2= mySearch(source,subString2);//從 source 字符串上面找 not,返回
值是 false
alert(result1);//
alert(result2);
});
接口定義 Array
interface StringArray {
[index: number]: string;
//length: number;
}
var myArray:StringArray;
myArray = ["Bob", "Fred"];
$(function(){
$.each(myArray,function(key,val){
alert(val);
});
})
class 實現 implements 接口
interface IClock {
currentTime: Date;
setTime(d: Date);
}
//--實現 IClock 接口
class Clock implements IClock{
currentTime:Date;
constructor(h: number, m: number) { }//--構造函數方法
setTime(d:Date){
this.currentTime=d;
}
}
//--------------------------------------------------
interface IClock1 {
new (hour: number, minute: number);
}
class Clock1 {
currentTime: Date;
constructor(h: number, m: number) { }
}
var cs: IClock1 = Clock1;
var newClock = new cs(7, 30);
console.log(newClock);
擴展接口 Extending Interfaces
interface IShape{
color:string;
}
interface PenStroke {
penWidth: number;
}
//--接口繼承接口,用,分割開多繼承.
interface ISquare extends IShape,PenStroke {
sideLength: number;
}
//---賦值..
var square = <ISquare>{};
square.color="red";
square.sideLength=100;
square.penWidth=50;
混合型 Hybrid Types
interface Counter {
(start: number): string;//聲明一個開始變量
interval:number;//聲明一個間隔變量
reset(): void;//聲明一個重置 function 方法
}
var c: Counter;
c(10);//開始.
c.interval=5.0;
c.reset();//重置.
TypeScript 類
//--這個是簡單的 class
class Employee {
fullName: string;
}
var employee = new Employee();
employee.fullName = "Long long";//賦值
//說明這個屬性是存在的..
if (employee.fullName) {
alert(employee.fullName);
}
Ts 文件編譯成 js 文件代碼
/// <reference path="../plugins/typescript/typings/jquery.d.ts" />
//--這個是簡單的 class
var Employee = (function () {
function Employee() {
}
return Employee;
})();
var employee = new Employee();
employee.fullName = "Long long"; //賦值
//說明這個屬性是存在的..
if (employee.fullName) {
alert(employee.fullName);
}
class使用 constructor super 關鍵字
1、-------------------
class Person{
userName:string;//聲明一個名稱
//構造方法
onstructor(paramVal:string){
this.userName=paramVal;
}
//--聲明一個 getPersonInfo 方法,並在聲明 age 變量
getPersonInfo(age:number=120):string{
return this.userName+"\n"+age;
}
}
class Student1 extends Person{
constructor(username:string){
super(username);
}
getPersonInfo(age=100){
var superMsg=super.getPersonInfo(age);
return this.userName+"\n"+age+"歲"+"\n\t\t"+"默認信息:" +superMsg;
}
}
class Student2 extends Person{
constructor(username:string){
super(username);
}
getPersonInfo(age=120){
var superMsg=super.getPersonInfo(age);
return this.userName+"\n"+age+"歲"+"\n\t\t"+"默認信息:" +superMsg;
}
}
var stu1=new Student1("周伯通");
var stu2=new Student2("老毒物");
var stuMsg1=stu1.getPersonInfo();
var stuMsg2=stu2.getPersonInfo(80);//傳一個默認值給 getPersonInfo 方法
2、-------------------默認是 public-------
class MyAnimal {
private name:string;
//構造方法
constructor(private theName : string){
this.name = theName;
}
getMsg(name : string):string{
return this.name=name;
}
}
//犀牛
class Rhino extends MyAnimal{
constructor(){
super("犀牛");
}
getMsg(name : string):string{
return name;
}
}
//員工
class Employees {
private name:string;
//構造方法
constructor(theName : string) {
this.name = theName;
}
}
var animal = new MyAnimal("山羊");//Goat 山羊
var retMsg1=animal.getMsg("鹿");
var rhino = new Rhino();
var employees = new Employees("洪七公");
animal = rhino;
//animal = employees;//此時這個值不能賦給 animal,並不能編譯經過.
3、----------- class高級技巧------
//當您聲明一個類,你其實是在同一時間建立多個聲明。第一個是類的實例的類型
class Greeter {
static standardGreeting = "Hello, there";
greeting: string;
greet() {
if (this.greeting) {
return "Hello, " + this.greeting;
}
else {
return Greeter.standardGreeting;
}
}
}
var greeter1: Greeter;
greeter1 = new Greeter();
alert(greeter1.greet());
var greeterMaker: typeof Greeter = Greeter;
greeterMaker.standardGreeting = "Hey there!";
var greeter2:Greeter = new greeterMaker();
alert(greeter2.greet());
TypeScript 塊
分多個 ts 文件實現 module (不分文件實現 module ,將其整合在一塊兒)
Validation.ts 代碼
module Validation{
export interface StringValidator {
isAcceptable(s: string): boolean;//是否接受.
}
}
ZipCodeValidator.ts 代碼
module Validation {
//匹配 0-9 的數字.
var numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
//若是長度=5 而且是數字就返回一個 true
return s.length === 5 && numberRegexp.test(s);
}
}
}
LettersOnlyValidator.ts 代碼
module Validation {
//匹配 A-Z,a-z 的英文
var lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
test-1.ts 代碼
// 聲明一個數組.
var strings = ['Hello', '98052', '101'];
// 使用這個驗證.
var validators: { [s: string]: Validation.StringValidator; } = {};
validators['Zip Code'] = new Validation.ZipCodeValidator();//這個是驗證郵政
編碼
validators['Letters only'] = new Validation.LettersOnlyValidator();//這個是
驗證英文
function showMsg():void{
//顯示每一個字符串是否經過每一個驗證
strings.forEach(s => {
for (var name in validators) {
console.log('"' + s + '" ' + (validators[name].isAcceptable(s) ? '
matches ' : ' does not match ') + name);
$("#msg1").html('"' + s + '" ' + (validators[name].isAcceptable(s) ?
' matches ' : ' does not match ') + name);
}//--for--end
});//--forEach--end
}
$(document).ready(function(){
showMsg();
});
import , require 關鍵字
某father.ts文件,子son.ts文件 import father = require('./father'); father.方法 (接口 &實現 結合 :export = 對象)
不使用 Module,若是咱們在 typescript 使用了 module 函數,則生成的代碼在
瀏覽器端執行時,須要有一些 script loader 的支持。對於瀏覽器端代碼,咱們通常生成 amd 風格的代碼,因此須要找一個支持 amd 的庫放在前端,我這裏首選的是 AMD 這樣的庫有不少,好比1. RequireJS 2. Nodules 3. JSLocalnet 4. curl.js
否則的話運行這個 html 會報 ReferenceError: define is not defined
module 別名的使用
//--聲明一個--Shapes 塊別名--module Shapes {//===========================多邊形=========================== export module Polygons {//===========================三角形=========================== export class Triangle { side : number = 3;//聲明邊一個變量,而且給一個默認值.. theName : string;//聲明一個名字 //聲明構造方法--傳一個名字的參數.. constructor(strName : string) { this.theName = strName; } //計算三角形,獲取面積,這裏爲了返回一個構造方法的傳進來的字符串,故返回類 型給了一個 any 類型.. getTriangleArea(side : number) : any{ return this.theName+ this.side*side; } }//===========================正方形=========================== export class Square { side : number = 8;//聲明邊一個變量,而且給一個默認值.. theName : string;//聲明一個名字 //聲明構造方法--傳一個名字的參數.. constructor(strName : string) { this.theName = strName; } //---計算正方形,獲取面積 getSquareArea(side : number) : any{ return this.theName+ this.side*side; } } }}