I am new to Typescript and I wrote a very rudimentary implementation of JSON stringify. The code works as expected, but my types are a bit messed up on the part where I recursively stringify nested arrays. Any help is appreciated :D
Here is a link to the TS playground and there it shows all the errors I get. PLAYGROUND LINK
type ValidJSON = ValidJSONObject | string | number | boolean | JsonArray
interface JsonArray extends Array<string | number | boolean | Date | ValidJSONObject | JsonArray> { }
interface ValidJSONObject {
[x: string]: string | number | boolean | Date | JsonArray
}
export const stringify = (input: ValidJSON) :string => {
if (input === null)
return 'null'
else if (input.constructor === String)
return '"' + input.replace(/"|\n/g, (x:string) => x === '"' ? '\\"' :'\\n') + '"'
else if (input.constructor === Number)
return String(input)
else if (input.constructor === Boolean)
return input ? 'true' : 'false'
else if (input.constructor === Array)
return '[' + input.reduce((acc, v) => {
if (v === undefined)
return [...acc, 'null']
else
return [...acc, stringify(v)]
}, []).join(',') + ']'
else if (input.constructor === Object)
return '{' + Object.keys(input).reduce((acc, k) => {
if (input[k] === undefined)
return acc
else
return [...acc, stringify(k) + ':' + stringify(input[k])]
}, []).join(',') + '}'
else
return '{}'
};