Categories
TypeScript Answers

How to add types for key-value pairs in TypeScript?

Spread the love

Sometimes, we want to add types for key-value pairs in TypeScript.

In this article, we’ll look at how to add types for key-value pairs in TypeScript.

How to add types for key-value pairs in TypeScript?

To add types for key-value pairs in TypeScript, we can use index signatures.

For instance, we write

interface Foo {
  [key: string]: number;
}

const foo: Foo = {};
foo["hello"] = 123;

to create the Foo interface that accepts any key-value pairs that have numbers as their values with

[key: string]: number;

Then we can create an object that implements the interface with

const foo: Foo = {};
foo["hello"] = 123;

Conclusion

To add types for key-value pairs in TypeScript, we can use index signatures.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *