Home > Software design >  Type 'number' is not assignable to type '{ [key: string]: string | number | boolean;
Type 'number' is not assignable to type '{ [key: string]: string | number | boolean;

Time:05-24

export interface BackendParameters {
  [key: string]: { [key: string]: string | boolean | number };
}

var param: BackendParameters = { par1: 2 } // error

var x: BackendParameters = { s: 1, 'x': 2 } // error

I get the error:

Type 'number' is not assignable to type '{ [key: string]: string | number | boolean; }'

What is the difference between these two types? How can I make interface for key-value pair object? The object could have many properties e.g let foo = {boo1:2,boo2:2}

CodePudding user response:

The correct typing should be

const x: BackendParameters = { someKey: { someOtherKey: 'some value' } }

If you don't want that, then your interface should be

interface BackendParameters {
  [key: string]: string | number | boolean;
}

CodePudding user response:

You're look for

const x: BackendParameters = Record<string, string | number | boolean>

This allows any string key.

  • Related