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

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}



Solution 1:[1]

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;
}

Solution 2:[2]

You're look for

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

This allows any string key.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 temp_user
Solution 2 Matthieu Riegler