Home > Software engineering >  How to reinforce type of object from an interface
How to reinforce type of object from an interface

Time:01-06

i have the following interface:

export interface CommandRequest {
  action: string;
  parameter: {
    source: string;
  }
}

I use it to build an object like this:

const commandRequest: CommandRequest = req.body;

Where req.body is the body of an http call.

Now, i want to store the commandRequest in a dictionary, that i keep like this:

const notepad = {
  commands: {}
};

export default notepad;

But i get the following error: TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}'.

How should i change the code to specify the type of the dictionary?

CodePudding user response:

Referencing the comment above, you can do this:

interface Notepad {
  commands: Record<string, CommandRequest>
}

const notepad = {
  commands: {}
}

export default notepad

Record docs: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type

  •  Tags:  
  • Related