typescript裏一些有趣的點

聯合類型

在原生的JS裏,null和undefined常常會致使BUG的產生,
在ts裏,你又想用null,又擔憂出錯的時候
你能夠考慮用聯合類型,當某值可能爲 number或null,你能夠聲明它的類型爲number | null數據結構

let a : number | null = 2;

類型兼容

實現接口時,只要包含了接口要求的數據結構便可兼容這個接口ide

interface Person {
    firstName: string;
    lastName: string;
}
function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "Jane", lastName: "User" };
document.body.innerHTML = greeter(user);

面向對象

繼承( extends關鍵字 )
public private  protected  static  readonly get和set  都有,連namespace也有;
抽象類( abstract關鍵字 )this

關於this

let deck: Deck = {
    // NOTE: The function now explicitly specifies that its callee must be of type Deck
    createCardPicker: function(this: Deck) {
        return () => {
           console.log(this)
        }
    }
}

指明this的類型必須是Deckspa

泛型

function identity<T>(arg: T): T {
    return arg;
}
let output = identity<string>("myString");  // type of output will be 'string'
//或者
let output = identity("myString");  // type of output will be 'string'

泛型方法、泛型類、泛型約束都有



 code

相關文章
相關標籤/搜索