typesccipt基礎知識指南(代碼詳細註釋版)

// 數組申明
var arr1:number[] = [1,2,3]
var arr2:Array<string> = ['hello','world']

// 枚舉:通常用來申明一些靜態的常量,如一年365天,一星期有7天等
enum Color {Red, Blue, Green};
// 獲取下標(默認從0開始,除非本身定義);下標類型能夠枚舉類,也能夠爲number
var x:Color = Color.Green;    // 值爲2 
var x1:number = Color.Green;  // 值爲2 

// 當本身定義了一個的下標的時候其餘兩個會順延到下兩位
enum Color1 {Red, Blue = 12, Green };  
var a:string = Color1[0]  // 結果爲Red
var a1:string = Color1[13]  // 結果爲Green

enum Color2 {Red = 11, Blue = 2, Green = 32};
var b:string = Color2[32]   // Green

// 遇到不知道的數據類型,能夠申明爲any,能夠賦值爲任何類型
var is:any = 'asda'
var arr3:any[] = [1,'hello', false]

// void 用於申明函數無返回值
function tell():string {
    return 'aaa'
}
function tell0():void{

}

// 函數申明
function add(a:number, b:number):string{
    return a+b+'aaa'
}

// 可是上面的函數沒法瞭解到參數是什麼意義【代碼可讀性比較差】,使用下面寫法能夠指定參數的實際意義:即n表示nam,a表示age
var myAdd:(name:string,age:number) => number = function(n:string,a:number):number{
    return a;
}
// 函數的可變參數:即參數個數是不肯定的
function peopleName(firstName:string, ...restOfName:string[]){
    return firstName+""+restOfName.join("-");
}

// console.log(peopleName()) // 此時會報錯,由於上面申明最少得有一個參數firstName
console.log(peopleName("hang"))   // hang
console.log(peopleName("iwn","ime","aa","bb"))  // iwnime-aa-bb

// 固然也能夠直接不寫固定參數,如上面的函數能夠寫成
function peopleName2(...restOfName:string[]){
    return restOfName.join("-");
}
console.log(peopleName2("x","y"))  // x-y

// lambads和this
var people = {
    name: ["iwn","ime","aa","bb"],
    getName:function(){   // 隨機返回一個name
        return () => {    // 此處必須使用箭頭函數,不然this指向找不到
            var i = Math.floor(Math.random()*4);
            return {
                n: this.name[i]
            }
        }
    }
}
var xx = people.getName();
console.log(xx().n)

// 函數重載
function attr(name:string):string;
function attr(name:number):number;
function attr(nameor:any):any{
    if(nameor && typeof nameor === "string"){
        console.log(nameor+" is string")
    }else{
        console.log(nameor+" is number")
    }
}
attr("hello")   // hello is string
attr(222)       // 222 is number

// 類
class Person{
    name:string;
    age: number;
    private sex: string;
    constructor(name:string, age:number, sex:string){  // 構造函數,也強制了類新建的時候必須傳入參數
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    print(){
        return this.name+":"+this.age+":"+this.sex;
    }
}

var p = new Person("Fane",23,"man")
console.log(p.print())  // Fane:23
// console.warn(p.name,p.sex) // 報錯:屬性「sex」爲私有屬性,只能在類「Person」中訪問

// 類的繼承
class Student extends Person{
    school: string;
    constructor(school:string){
        super("Lilei", 24,"man");     // 調用父類的構造函數
        this.school = school;
    }
    print(){
        return this.name+":"+this.age+":"+this.school
    }
}
var s = new Student("Jialidun School")
console.error(s,s.print())

// 訪問修飾符public private【不申明的話默認是public】

// 因爲私有屬性不能被當前對象外部訪問,可是咱們能夠封裝類的get/set方法來實現
class Hello{
    private _age: number
    tell(){
        return this._age
    }
    get age():number{
        return this._age
    }
    set age(newage: number){  // 此處能夠作其餘邏輯操做
        if(newage > 200 || newage < 0){
            alert("Error Age")
        }else{
            this._age = newage
        }
    }
}
var h = new Hello();
h.age = 100
// h.age = 211 // 此時會彈出上面的alert內容
console.log(h.age, h.tell())


// static:聲明爲static的屬性是不能夠使用this訪問的,必須使用類自己訪問;下面咱們來對比一下:
// (不是static,實際上是public)
class Person2{
    name:string;
    tell(){  // 構造函數,也強制了類新建的時候必須傳入參數
        console.log(this.name)
    }
}
var p2 = new Person2();
p2.name = "zhaoqiang"
p2.tell()  // zhaoqiang
// (static 申明)
class Person3{
    static myname:string;
    tell(){  // 構造函數,也強制了類新建的時候必須傳入參數
        console.log(Person3.myname)
    }
}
var p3 = new Person3();
Person3.myname = "zhaoqiang--3"
p3.tell()  // zhaoqiang--3

// 類的引用數據類型,如上面的Person2
var myP2: Person2;  // 此處就是把類做爲數據類型來申明
myP2 = new Person2();


// 接口interface:能夠定義js的任何類型
// @接口做用:1.規範參數的使用

// (沒有接口的時候)
function printLabel(obj:{label:string}){
    console.log(obj.label)
}
var myObj = {label: "Hello!"}
printLabel(myObj)    // Hello
// 使用接口替代上面的方法
interface LabelValue{
    label: string;
    age?: number;   // 接口可選屬性
}
function printLabel2(labelObj: LabelValue){
    console.log(labelObj)
}
var myObj2 = {label: "Hello-2!"}
printLabel(myObj2)    // {label: "Hello-2!"}

// 接口定義函數類型
interface SearchFunc{   // 定義一個輸入兩個string參數,返回boolean的函數接口類型
    (source: string,subString:string): boolean
}

var mySearch:SearchFunc;
mySearch = function(src:string,sub:string){  // ts只對參數作類型檢查,不會
    var res = src.search(sub);
    if(res != 1){
        return true;
    }else{
        return false;
    }
}

// 接口定義數組類型
interface StringArray{
    [index:number]:string;
}

// implements 接口實現爲類
interface ClockInterface{
    currentTime: Date;
    setTime(d:Date);
}

class Clock implements ClockInterface{
    currentTime: Date;
    setTime(d:Date){
        this.currentTime = d;
    }
    constructor(h:number, m:number){

    }
}

// 接口繼承
// 單繼承
interface Shape{
    color: string
}
interface Square extends Shape{
    sideLength: number;
}
var ss = <Square>{};
ss.color = "blue";
ss.sideLength = 10;

// 接口多繼承
interface Shape{
    color: string
}
interface Stoke{
   width: number; 
}
interface Square extends Shape,Stoke{
    sideLength: number;
}


// 接口的混合類型
interface Counter{
    interval: number;
    reset():void;
    (start:number):string;
}

var c:Counter;
c(10);
c.reset();
複製代碼


// 泛型<T>:不肯定參數類型時候,定義泛型【此處不必定必須爲T,這只是個習慣】
function THello<T>(arg: T):T{
    return arg;
}
// 在使用的時候再肯定類型
var toutput = THello<string>("Hello world");
console.warn(toutput)

// 泛型應用再舉例
function THello1<T>(str: T[]):T[]{
    console.log(str.length)
    return str;
}
var list:Array<string> = THello1<string>(["1","2","3"]);

// 泛型與lambads表達式
// 指定一個泛型函數。其   參數爲K類型,返回也爲K類型的THello泛型
var myHello:<K>(arg:K) => K = THello;
console.log(myHello("hello!!!"))
// 與上面同樣,換種寫法
var myHello2:{<T>(arg: T):T} = THello;

// 泛型類
class HelloNumber<T>{
    Ten:T;
    add:(x:T,y:T) =>T;
}
var myHelloNumber = new HelloNumber<number>();
myHelloNumber.Ten = 10;
myHelloNumber.add = function(x,y){
    return x+y;
}
console.log(myHelloNumber.Ten)   // 10
console.log(myHelloNumber.add(10,12))   // 22

複製代碼
相關文章
相關標籤/搜索