wanghy6503
7/16/2019 - 6:32 AM

Typescript Index Signatures Example

class Animal {
    name: string = "";
}
class Dog extends Animal {
    breed: string = "";
}

interface NumberDictionary {
    [index: string]: number|string;
    length: number;    // ok, length is a number
    name: string;      // error, the type of 'name' is not a subtype of the indexer
}

let test:NumberDictionary = {length:2, name: 'anthonywang'}

console.log(test[name])
console.log(test[0])

interface NumberDictionary1 {
    [index: string]: number;
    length: number;    // ok, length is a number
}

interface ReadonlyStringArray {
    [index: number]: string;
}
let myArray: ReadonlyStringArray = ["Alice", "Bob"];
myArray[2] = "Mallory"; // error!

console.log(myArray[0])
console.log(myArray[1])
console.log(myArray[2])