Categories
TypeScript Answers

How to create a TypeScript interface for objects with some known and some unknown property names?

Spread the love

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.

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 *