1

My goal is to create a type called JSONObject for any JSON like object. The best I found so far is:

interface JSONObject {
    [x: string]: JSONValue;
}

interface JSONArray extends Array<JSONValue> { }
type JSONValue =
    | string
    | number
    | boolean
    | JSONObject
    | JSONArray;

To be used in low level function like this:

function saveJson(data: JSONObject) { ... }

Which works for most cases but this case, it does not work

export interface FooBar {
    foo: number,
    bar: number,
}
const data: FooBar = await fetchSomething();
saveJson(data);

With the compile time error:

Argument of type 'FooBar' is not assignable to parameter of type 'JSONObject'.   Index signature is missing in type 'FooBar'.

My goal to remove the error without touching FooBar

TSR
  • 17,242
  • 27
  • 93
  • 197

0 Answers0