TypeScript 1.3

受保护的

🌐 Protected

类中的新 protected 修饰符的作用与熟悉的语言(如 C++、C# 和 Java)中的用法相同。类的 protected 成员仅在其声明的类的子类中可见:

🌐 The new protected modifier in classes works like it does in familiar languages like C++, C#, and Java. A protected member of a class is visible only inside subclasses of the class in which it is declared:

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 的数组:

🌐 Tuple types express an array where the type of certain elements is known, but need not be the same. For example, you may want to represent an array with a string at position 0 and a number at position 1:

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

访问具有已知索引的元素时,将检索正确的类型:

🌐 When accessing an element with a known index, the correct type is retrieved:

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

请注意,在 TypeScript 1.4 中,当访问已知索引集之外的元素时,将改用联合类型:

🌐 Note that in TypeScript 1.4, when accessing an element outside the set of known indices, a union type is used instead:

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