TypeScript
Types
Index Signature
1
2
3
4
5
6
7
8
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ['Bob', 'Fred'];
let myStr: string = myArray[0];
1
2
3
4
5
6
7
8
interface NumberDictionary {
[index: string]: number;
length: number; // ok, length is a number
// name: string // error, the type of 'name' is not a subtype of the indexer
}
let myDict: NumberDictionary;
myDict = { length: 10, 1: 2 };
Tuples
1
2
3
4
5
6
let x: [string, number];
x = ['hello', 10]; // OK
x = [10, 'hello']; // Error
x.pop();
x.pop();
x.length;
Use readonly
to make the tuple immutable.
1
2
3
4
let y: readonly [string, number] = ['hello', 10];
y.length;
y[0] = 'world'; // Cannot assign to '0' because it is a read-only property.ts(2540)
y.push('world'); // Property 'push' does not exist on type 'readonly [string, number]'.ts(2339)