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.