Typescript JSON type not working properly (recursive type definition problem?)

82 views Asked by At

I created a legit JSONValue type with some recursive logic. I've tried everything and read a lot of documentation, still don't understand why this not works as expected (the compiler doesn't complain when I define the object, but it complains when I try to use it!).

Can anybody give me some insights here? What I'm doing it wrong?

type JSONPrimitive = {} | null | undefined // any primitive, null or undefined
type JSONObject = { [k: string]: JSONValue }
type JSONArray = JSONValue[]
type JSONValue = JSONArray | JSONObject | JSONPrimitive

let myObject: JSONValue = {
  someString: 'it complains',
  someObj: {
    anotherString: 'why?'
  },
  someNull: null
}

console.log( myObject.someString )
                      // ^ Error here `Property 'someString' does not exist on type '{}`

On the last console log the compiler says: Property 'someString' does not exist on type '{}

Try it on the Ts Playground (error at line 17).

===
EDIT, another example: If I add some function like this, the compiler complains, so what is the point here? How can I use this:

logMyObjectNested(myObject)
// This is totally fine...

function logMyObjectNested( objParam: JSONValue ) {
  console.log( objParam.someObj )
                        // ^ it complains ...
}
1

There are 1 answers

0
Lajos Arpad On

It just warns you that the field that you presume to exist does not necessarily exist as per the type declaration. You can convert it to the correct type and you will have no complaints afterwards:

type JSONPrimitive = {} | null | undefined // any primitive, null or undefined
type JSONObject = { [k: string]: JSONValue }
type JSONArray = JSONValue[]
type JSONValue = JSONArray | JSONObject | JSONPrimitive

let myObject: JSONValue = {
  someString: 'it complains',
  someObj: {
    anotherString: 'why?'
  },
  someNull: null
}

console.log( (myObject as JSONObject).someString )