DEV Community

loading...
Cover image for Typescript - Tips & Tricks - Index Signature

Typescript - Tips & Tricks - Index Signature

puppo profile image Luca Del Puppo ・1 min read

Welcome back guys, today I'll speak about the "Index Signature".
In some cases, we need to create some special types like dictionaries.
These special types have some keys that identifies the elements and the datas.
A simple example:

export type User = {
    name: string,
    email: string;
    session: string
}

export type UserDictionary = {
    [username: string]: User
}

const userDictionary: UserDictionary = {
  'myusername': { email: "myemail@email.it", name: "myname", session: "session" },
  'myusername1': {
    email: "myemail1@email.it",
    name: "myname1",
    session: "session",
  },
};

console.log(userDictionary.myusername); // { email: 'myemail@email.it', name: 'myname', session: 'session' }
console.log(userDictionary["myusername"]); // { email: 'myemail@email.it', name: 'myname', session: 'session' }
console.log(userDictionary.myusername1); // { email: 'myemail1@email.it', name: 'myname1', session: 'session' }
console.log(userDictionary["myusername1"]); // { email: 'myemail1@email.it', name: 'myname1', session: 'session' }
delete userDictionary.myusername;

Enter fullscreen mode Exit fullscreen mode

In this case, the UserDictionary is a special type where the usernames are the keys of the objects and the user data are the values.
This type is powerful because it permits the consumer to access directly to the data if it knows the keys and it permits to store a unique value of a specific key.
With the index signature, we can create special types where the keys can be string or number.
An important thing that you must remember is that the keys of these objects can be iterated with the for-in loop or with the Object.keys method.

console.log(Object.keys(userDictionary)); // [ 'myusername', 'myusername1' ]
for (const key in userDictionary) {
  console.log(key);
}
/*
'myusername'
'myusername1'
*/
Enter fullscreen mode Exit fullscreen mode

It's all from the Index Signature for today.
Bye-bye guys!

Discussion (2)

pic
Editor guide
Collapse
lyrod profile image
Lyrod

Need to talk about Record<>

Collapse
puppo profile image
Luca Del Puppo Author

yes, good point. I take note for another post. Thanks