programing

유형 스크립트에서 JSON 개체를 선언하는 올바른 방법

iphone6s 2023. 8. 30. 21:27
반응형

유형 스크립트에서 JSON 개체를 선언하는 올바른 방법

제 Angular 2 앱에 다음과 같은 JSON 객체가 있는데, 그것을 typescript로 선언해야 할 적절한 것이 무엇인지 알고 싶습니다.

data = [
  {
    'id':1,
    'title':'something'
    'node': [
              {
              'id':1,
              'title':'something'
              'node': []
              }
            ]
  },
  {
    'id':2,
    'title':'something'
    'node': [
              {
              'id':1,
              'title':'something'
              'node': []
              }
            ]
  }
]

다음은 귀하가 요구하는 것을 쉽고 단순하게 구현한 것입니다.

interface IDataNode {
    id: number;
    title: string;
    node: Array<IDataNode>;
}

코드에서 해당 노드를 인스턴스화하려는 경우:

class DataNode implements IDataNode {
    id: number;
    title: string;
    node: Array<IDataNode>;

    constructor(id: number, title: string, node?: Array<IDataNode>) {
        this.id = id;
        this.title = title;
        this.node = node || [];
    }

    addNode(node: IDataNode): void {
        this.node.push(node);
    }
}

이를 사용하여 구조를 하드코딩합니다.

let data: Array<IDataNode> = [ 
    new DataNode(1, 'something', [
        new DataNode(2, 'something inner'),
        new DataNode(3, 'something more')
    ]),
    new DataNode(4, 'sibling 1'),
    new DataNode(5, 'sibling 2', [
        new DataNode(6, 'child'),
        new DataNode(7, 'another child', [
            new DataNode(8, 'even deeper nested')
        ])
    ])
];

업데이트: 2021년 7월 26일

원래 답변에 명시된 논의 내용을 다시 검토해보니, 현재 개선된 구현이 있는 업데이트가 있습니다.

type JSONValue = 
 | string
 | number
 | boolean
 | null
 | JSONValue[]
 | {[key: string]: JSONValue}

interface JSONObject {
  [k: string]: JSONValue
}
interface JSONArray extends Array<JSONValue> {}

이것은 저에게 매우 효과적이었습니다.

토론 참조: https://github.com/microsoft/TypeScript/issues/1897#issuecomment-822032151

원답:20년 9월 29일

저는 이것이 오래된 질문이라는 것을 알지만, 저는 방금 저에게 아주 잘 맞는 해결책을 찾았습니다.다음을 선언합니다.

type JsonPrimitive = string | number | boolean | null
interface JsonMap extends Record<string, JsonPrimitive | JsonArray | JsonMap> {}
interface JsonArray extends Array<JsonPrimitive | JsonArray | JsonMap> {}
type Json = JsonPrimitive | JsonMap | JsonArray

그러면 다음 중 하나(구문 오류를 위해 약간 수정된 OP 버전 포함)가 작동합니다.

    let a: Json = {};
    
    a[1] = 5;
    a["abc"] = "abc";
    a = {
      a: {
        a: 2,
      },
      b: [1, 2, 3],
      c: true,
    };
    a = [
      {
        "id": 1,
        "title": "something",
        "node": [
          {
            "id": 1,
            "title": "something",
            "node": [],
          },
        ],
      },
      {
        "id": 2,
        "title": "something",
        "node": [
          {
            "id": 1,
            "title": "something",
            "node": [],
          },
        ],
      },
    ];

이 답변은 Typescript: https://github.com/microsoft/TypeScript/issues/1897#issuecomment-648484759 에서 Json을 기본 유형으로 만드는 것에 대한 논의에 대해 제안한 Andrew Kaiser에게 공로를 돌려야 합니다.

올바른 방법은 인터페이스를 사용하는 것입니다. 자바스크립트로 컴파일할 때 추가 코드를 생성하지 않으며 정적 타이핑 기능을 제공합니다.

https://www.typescriptlang.org/docs/handbook/interfaces.html

언급URL : https://stackoverflow.com/questions/38123222/proper-way-to-declare-json-object-in-typescript

반응형