我对类型记录很陌生,我编写了一个JSON的基本实现。代码按预期工作,但我的类型在递归字符串嵌套数组的部分上有点混乱。如有任何帮助,我们将不胜感激:
这里有一个指向TS操场的链接,它显示了我得到的所有错误。操场链接
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 '{}'
};
发布于 2020-07-15 09:30:55
如果不能推断累加器类型,则减少方法需要类型参数。
例如。以下代码的累加器不知道数组的类型。
[1,2,3].reduce((acc, cur) => ([...acc, cur+'']), [])
因此,您需要传递类型参数,如下所示。
[1,2,3].reduce<string[]>((acc, cur) => ([...acc, cur+'']), [])
我也修正了所有的错误。这些变化如下。
string[]
添加到约简方法的参数类型中。(input as ValidJSONObject)
生成的javascript代码与您的代码相同。
我希望这能帮上忙!
type ValidJSON = ValidJSONObject | string | number | boolean | Date | 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<string[]>((acc, v) => {
if (v === undefined)
return [...acc, 'null']
else
return [...acc, stringify(v)]
}, []).join(',') + ']'
else if (input.constructor === Object)
return '{' + Object.keys(input).reduce<string[]>((acc, k: keyof ValidJSONObject) => {
if ((input as ValidJSONObject)[k] === undefined)
return acc
else
return [...acc, stringify(k) + ':' + stringify((input as ValidJSONObject)[k])]
}, []).join(',') + '}'
else
return '{}'
};
https://stackoverflow.com/questions/62919932
复制相似问题