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 日