在原生的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
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