Home > Mobile >  How to define a completely unknown incoming JSON field in a type?
How to define a completely unknown incoming JSON field in a type?

Time:01-12

I have models coming from a backend with a metadata field that can be any valid JSON with no guaranteed schema:

{
  "unknown_field" : "Apple",
  "unknown_field_2" : 13
}

I'm trying to write a type to intake this:

type MyModel{
   id : string
   name : string
   metadata : {} // <- obviously not working
}

What's the proper way to define metadata here? The examples I search for keep proposing defining a known schema with optional fields, which is not what I have.

Edit:

metadata : {} does not work and gives this message:

"don't use '{}' as a type. '{}' actually means any non-nullish value"

CodePudding user response:

Are you using ESLint? By default your type definition seems valid, other than missing a few symbols:

type MyModel = {
  id: string;
  name: string;
  metadata: {};
}

You can configure ESLint to ignore this rule (see the answer here).

Alternatively, try either of these types instead:

type MyModel1 = {
  id: string;
  name: string;
  metadata: object;
}

type MyModel2 = {
  id: string;
  name: string;
  metadata: { [key: string]: any };
}

CodePudding user response:

If it can really be anything your only option is using any type.

If you're getting some dictionary, you could try to narrow it down to something like this .:

metadata: { [key:string]: any }

Which would at least indicate that you're dealing with something that has keys at the first level

  • Related