Sometimes, we want to create a TypeScript interface for objects with some known and some unknown property names.
In this article, we’ll look at how to create a TypeScript interface for objects with some known and some unknown property names.
How to create a TypeScript interface for objects with some known and some unknown property names?
To create a TypeScript interface for objects with some known and some unknown property names, we can use index signatures for the unknown properties.
For instance, we write
interface IObject {
fixedKey1: string;
fixedKey2: string;
[key: string]:
| string
| {
param1: number[];
param2: string;
param3: string;
};
}
to add an index signature with [key: string]
.
This lets an object with the IObject
accept any additional properties other than the ones added above.
And we set the type of the dynamic properties to string
or
{
param1: number[];
param2: string;
param3: string;
}
Conclusion
To create a TypeScript interface for objects with some known and some unknown property names, we can use index signatures for the unknown properties.