DEV Community

loading...
Cover image for TypeScript Index Signature

TypeScript Index Signature

Afraz Khan
data is reality.
・Updated on ・2 min read

Javascript objects obj:{} are usually indexed using strings. But certainly, its possible to index them using number and even object types as keys. Because when it comes to index a particular element of a javascript object, JS always stringifies a non-string key by calling toString() method. So number as key will get stringified and object as key must have a toString() method which returns a valid string key.

let obj = {
  toString(){
    console.log('toString called')
    return 'Hello'
  }
}
let foo: any = {};
foo[obj] = 'World'; // toString called
console.log(foo[obj]); // toString called, World
console.log(foo['Hello']); // World
Enter fullscreen mode Exit fullscreen mode

Getting shot in the feet

In typescript, object as key does not work as above in javascript. Typescript usually throws error doing that.

Lets suppose that if somehow developer uses an object as key without toString() method implementation. In javascript, then default value for toString() method coming from V8 engine serves the purpose for key and horribly its value is [object Object] πŸ˜–. I am sure that you never would have wanted or used [object Object] as an object key in your entire life. πŸ˜‚

Basically, typescript wants to save developers from getting shot in the feet, specially the beginners. It wants developers to be explicit about object index key type.

So, an error like below one or it maybe different, would be thrown everytime, object is used for object indexing in typescript.

"ERROR: Index signature of object type implicitly has an 'any' type"

let obj = {message:'Hello'}
let foo: any = {};

// ERROR: the index signature must be string, number ...
foo[obj] = 'World';

// Here is where you actually stored it!
console.log(foo["[object Object]"]);  // World
Enter fullscreen mode Exit fullscreen mode

For number indexes, typescript works fine as they work well for indexing and obviously easily stringifiable.

Index Signature

In typescript, Index Signature identifies key type for indexing of an object. Everytime an object in typescript is created and indexing is expected on that object then developers must specify Index Signature .

Syntax to declare Index Signature is as follows:

type testType = {
    [<index_name>: <index_type>]: <element_type>
}
// index_name: could be any string value.
// index_type: string or number
// element_type: it could be any premitive type (string, number etc) or a custom type you want your elements to conform to.
Enter fullscreen mode Exit fullscreen mode
  • Index Signatures resolve the the implicite index signature error described in last section.
  • You can use them to restrict your object elements to only one type.

    type foot = { [shot: string]: string };
    
    const shot: foot = {
        'name': 'john',
        'email': 1231    // Error
    }
    
  • You can shape your object as you want along with your index signature.

    type foot = {
        color: string 
        [shot: string]: string 
    };
    
    const shot: foot = {
        'name': 'john' // Error: color attribute not available
    }
    

happy coding 🀞

Discussion (0)