Let’s put our knowledge to the test, by defining a type that describes any allowable JSON value.
Here’s the relevant section of the specification:
md
A JSON value MUST be an- object- array- number- string,or one of the following three literal names:- false- true- null
Here’s your starting point code:
tsTry
typeJSONObject = anytypeJSONArray = anytypeJSONValue = any////// DO NOT EDIT ANY CODE BELOW THIS LINE //////functionisJSON (arg :JSONValue ) {}// POSITIVE test cases (must pass)isJSON ("hello")isJSON ([4, 8, 15, 16, 23, 42])isJSON ({greeting : "hello" })isJSON (false)isJSON (true)isJSON (null)isJSON ({a : {b : [2, 3, "foo"] } })// NEGATIVE test cases (must fail)Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.// @ts-expect-error isJSON (() => "")Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.// @ts-expect-error isJSON (class {})Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.// @ts-expect-error isJSON (undefined )// @ts-expect-errorisJSON (BigInt (143))Unused '@ts-expect-error' directive.2578Unused '@ts-expect-error' directive.// @ts-expect-error isJSON (isJSON )
Spoiler warning // Click to reveal answer
tsTry
typeJSONPrimitive = string | number | boolean | nulltypeJSONObject = { [k : string]:JSONValue }typeJSONArray =JSONValue []typeJSONValue =JSONArray |JSONObject |JSONPrimitive ////// DO NOT EDIT ANY CODE BELOW THIS LINE //////functionisJSON (arg :JSONValue ) {}// POSITIVE test cases (must pass)isJSON ("hello")isJSON ([4, 8, 15, 16, 23, 42])isJSON ({greeting : "hello" })isJSON (false)isJSON (true)isJSON (null)isJSON ({a : {b : [2, 3, "foo"] } })// NEGATIVE test cases (must fail)// @ts-expect-errorisJSON (() => "")// @ts-expect-errorisJSON (class {})// @ts-expect-errorisJSON (undefined )// @ts-expect-errorisJSON (BigInt (143))// @ts-expect-errorisJSON (isJSON )