TypeScript 1.3

Protected (受保護的)

類中新的 protected 修飾符的作用與 C++、C# 和 Java 等常見語言中的用法相同。類中的 protected 成員僅在宣告該成員的類的子類中可見。

ts
class Thing {
protected doSomething() {
/* ... */
}
}
class MyThing extends Thing {
public myMethod() {
// OK, can access protected member from subclass
this.doSomething();
}
}
var t = new MyThing();
t.doSomething(); // Error, cannot call protected member from outside class

Tuple types (元組型別)

元組型別表示一個數組,其中某些元素的型別是已知的,但這些元素不必是相同型別。例如,你可能想表示一個數組,其位置 0 處為 string,位置 1 處為 number

ts
// Declare a tuple type
var x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error

當訪問具有已知索引的元素時,會獲取正確的型別。

ts
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

請注意,在 TypeScript 1.4 中,當訪問已知索引集合之外的元素時,會改用聯合型別。

ts
x[3] = "world"; // OK
console.log(x[5].toString()); // OK, 'string' and 'number' both have toString
x[6] = true; // Error, boolean isn't number or string

TypeScript 文件是一個開源專案。歡迎透過 提交 Pull Request 來幫助我們改進這些頁面 ❤

此頁面的貢獻者
MHMohamed Hegazy (52)
OTOrta Therox (12)
2+

最後更新:2026 年 3 月 27 日