저는 Typescript를 처음 접했고 JSON stringify의 매우 기본적인 구현을 작성했습니다. 코드는 예상대로 작동하지만 내 유형은 중첩 배열을 재귀 적으로 문자열 화하는 부분에서 약간 엉망입니다. 어떤 도움을 주시면 감사하겠습니다 : D
여기에 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 '{}'
};
누산기 유형을 추론 할 수없는 경우 reduce 메소드에 유형 인수가 필요합니다.
예를 들면. 다음 코드의 누산기는 배열의 유형을 알려주지 않습니다.
[1,2,3].reduce((acc, cur) => ([...acc, cur+'']), [])
따라서 다음과 같이 유형 인수를 전달해야합니다.
[1,2,3].reduce<string[]>((acc, cur) => ([...acc, cur+'']), [])
또한 모든 오류를 수정했습니다. 다음과 같이 변경됩니다.
string[]
reduce 메소드의 유형 인수에 추가되었습니다 .(input as ValidJSONObject)
생성 된 자바 스크립트 코드는 귀하의 코드와 동일합니다.
도움이 되길 바랍니다!
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 '{}'
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다