'Index signature for type 'string' is missing in type 'Object'.ts(2322)

I want to assign my custom object to JsonObject efied in Prisma package. this code generates error that I don't know why:

interface JsonArray extends Array<JsonValue> {}
type JsonValue = string | number | boolean | JsonObject | JsonArray | null
type JsonObject = {[Key in string]?: JsonValue}
// ^ These are defined in Prisma package and I cannot change them

interface Object {
  name: string
}

let object : Object
let jsonObject : JsonObject 

// This line has error
jsonObject = object;

// Type 'Object' is not assignable to type 'JsonObject'.
// The 'Object' type is assignable to very few other types.
// Did you mean to use the 'any' type instead?
// Index signature for type 'string' is missing in type 'Object'.ts(2322)


Solution 1:[1]

There are a few issues here.

  • Object is a built-in javascript data type. You should name your interface something else, e.g. MyObject,
  • You are declaring a variable object but it is not initialised, i.e. it doesn't have any value. You cannot use it in operation like x = object,
  • Your interface does not fully overlap with JsonObject. You can either modify the interface or use type.
interface JsonArray extends Array<JsonValue> {}
type JsonValue = string | number | boolean | JsonObject | JsonArray | null
type JsonObject = {[Key in string]?: JsonValue}
// ^ These are defined in Prisma package and I cannot change them

type MyObject = {
  name: string
}

let anObject: MyObject = {name: "foo"}
let jsonObject: JsonObject 

// no error
jsonObject = anObject

Try it in the typescript playground.

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 szaman