Skip to content

Instantly share code, notes, and snippets.

@ticidesign
Last active October 2, 2021 07:24
Show Gist options
  • Save ticidesign/11aa766cce2fbc5af35f27dcb9c04c7a to your computer and use it in GitHub Desktop.
Save ticidesign/11aa766cce2fbc5af35f27dcb9c04c7a to your computer and use it in GitHub Desktop.
Recursive types in TypeScript to defining a type that describes any allowable JSON value.
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#recursive-conditional-types
type Primitive = string | number | boolean | null
type JSONObject = {[k: string] : JSONValue}
type JSONArray = JSONValue[]
type JSONValue =
| Primitive
| JSONObject
| JSONArray
function isJSON(arg: JSONValue) {}
isJSON("hello")
isJSON([4, 8, 15, 16, 23, 42])
isJSON({ greeting: "hello" })
isJSON(false)
isJSON(true)
isJSON(null)
isJSON({ a: { b: [2, 3, "foo"] } })
isJSON(() => "")
isJSON(class {})
isJSON(undefined)
isJSON(new BigInt(143))
isJSON(isJSON)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment