TypeScript 1.3

TypeScript 1.3

受保护

类中的新protected修饰符就像它在 C ++, C# 和 Java 等熟悉的语言中一样。protected类的成员仅在声明它的类的子类中可见:

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

元组类型

元组类型表示一个数组,其中某些元素的类型是已知的,但不一定是相同的。例如,您可能想要用string位置0和number位置1 来表示一个数组:

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

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

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

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

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