IT박스

객체 배열을 어떻게 정의 할 수 있습니까?

itboxs 2020. 6. 15. 22:00
반응형

객체 배열을 어떻게 정의 할 수 있습니까?


TypeScript에서 객체 배열을 만들고 있습니다.

 userTestStatus xxxx = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
 };

누군가 내가 유형을 올바르게 선언하는 방법을 말해 줄 수 있습니까? 인라인으로 할 수 있습니까, 아니면 두 가지 정의가 필요합니까?

xxx나중에 TypeScript userTestStatus[3].nammme에서 실수로 같은 것을 사용하면 경고 할 수 있도록 유형 선언으로 를 대체하려고합니다 .


번호와 비슷한 속성을 가진 객체 리터럴 대신 기본 배열을 사용하는 것이 좋습니다 . 따라서 번호를 지정하는 것 (및 수많은 다른 배열 함수)을 기성품으로 처리 할 수 ​​있습니다.

여기에서 찾고 있는 것은 배열의 모든 요소를 ​​정의하는 배열 의 인라인 인터페이스 정의입니다.

let userTestStatus: { id: number, name: string }[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

값을 사용하여 배열을 즉시 초기화하는 경우 명시 적 유형 정의가 필요하지 않습니다. TypeScript는 초기 할당에서 대부분의 요소 유형을 자동으로 유추 할 수 있습니다.

let userTestStatus = [
    { "id": 0, "name": "Available" },
    ...
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

위의 것은 배열이 아닌 객체입니다.

배열을 사용 하여 객체를 둘러싸려면 [& ]사용 하십시오.

userTestStatus = [
  { "id": 0, "name": "Available" },
  { "id": 1, "name": "Ready" },
  { "id": 2, "name": "Started" }
];

그 TypeScript 외에도 JavaScript의 수퍼 세트이므로 유효한 JavaScript는 유효한 TypeScript이므로 다른 변경이 필요하지 않습니다.

게시 된 모델에 대한 정의가 필요한 OP의 피드백 설명

여기에 정의 된 유형을 사용하여 객체 모델을 나타낼 수 있습니다.

type MyType = {
    id: number;
    name: string;
}

type MyGroupType = {
    [key:string]: MyType;
}

var obj: MyGroupType = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
};
// or if you make it an array
var arr: MyType[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

일부 tslint규칙은 예제 메시지 인 [] 사용을 비활성화합니다.Array type using 'T[]' is forbidden for non-simple types. Use 'Array<T>' instead.

그런 다음 다음과 같이 작성하십시오.

var userTestStatus: Array<{ id: number, name: string }> = Array(
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
);

실제로 원하는 것은 단순히 열거 일 수 있습니다.

If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.

enum TestStatus {
    Available,     // 0
    Ready,         // 1
    Started,       // 2
}

class Test {
    status: TestStatus
}

var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
                                    // and the sequence ID is automatic

The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available. And Typescript will enforce the type when you pass those around.

If you insist on defining a new type as an array of your custom type

You wanted an array of objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.

class TestStatus {
    id: number
    name: string

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

type Statuses = Array<TestStatus>;

var statuses: Statuses = [
    new TestStatus(0, "Available"),
    new TestStatus(1, "Ready"),
    new TestStatus(2, "Started")
]

참고URL : https://stackoverflow.com/questions/35435042/how-can-i-define-an-array-of-objects

반응형