Categories
TypeScript Answers

How to fix the “Object literal may only specify known properties” error with TypeScript?

Spread the love

To fix the "Object literal may only specify known properties" error with TypeScript, we can add dynamic keys properties into our interfaces with index signatures.

For instance, we write

interface Model {
  name: string;
  [others: string]: any;
}

const createModel = (x: Model) => {
  //...
};

createModel({ name: "hello", length: 100 });

to create the Model interface that has the required name property.

And we have

[others: string]: any;

to add an index signature that lets the interface allow any optional property other than name into our Model type object in addition to name.

Therefore,

createModel({ name: "hello", length: 100 });

won’t throw an error since the object that createModel is called with has name and another property.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.