It seems like creating a generic JSON type interface in TypeScript may be challenging due to the return type of the native JSON.parse
function being any
. Despite this, I have been exploring ways to achieve this and found a solution on GitHub that is very close:
type JSONValue = boolean | number | string | JSONObject | JSONArray
interface JSONObject {
[k: string]: JSONValue
}
interface JSONArray extends Array<JSONValue> {}
const json: JSONObject = {}
console.log(json.gray[9])
However, this solution fails to compile in strict mode with the following error message:
~ ❯❯❯ tsc --strict test.ts
test.ts(11,13): error TS7017: Element implicitly has an 'any' type because type 'JSONValue' has no index signature.
It appears that even though JSONObject
and JSONArray
have index signatures, the union type JSONValue
does not accept one according to the compiler. I am interested to know if there is a way around this limitation for my own learning. Considering that the GitHub issue dates back to 2015, it's possible that TypeScript has evolved since then.
Any insights or advice from experienced TypeScript developers would be greatly appreciated!