简体   繁体   English

Typescript 不同类型对象数组的类型

[英]Typescript Type for Array of Objects with different Types

I'm trying to write the type for an array that contains objects, but with different types.我正在尝试为包含对象但具有不同类型的数组编写类型。

[
        {
            "id": "test",
            "answer": "1"
        },
        {
            "id": "test_multi",
            "answers": [
                {
                    "id": "skill_1"
                },
                {
                    "id": "skill_2"
                }
            ]
        },
]

My first approaches were:我的第一个方法是:

prop: { id: string; answer: string | boolean | { id: string; answers: { id: string }[]} }[];

I guess in this case I'm assigning the different object to the answer prop.我想在这种情况下,我将不同的 object 分配给answer道具。

Next approach下一个方法

    { id: string; answer: string | boolean;  } | { id: string; answers: { id: string }[] }[];

But in this case I guess I'm not allowing the array to be filled by the first type of object.但在这种情况下,我想我不允许数组被第一种 object 填充。

How can I write the type for "this array can contain this object AND/OR this object"?如何编写“此数组可以包含此 object 和/或此对象”的类型?

You can use parentheses like this:您可以像这样使用括号:

({ id: string; answer: string | boolean;  } | { id: string; answers: { id: string }[] })[];

I would suggest you to change the input.我建议你改变输入。 It would be hard to work with different variants of 'answer'/'answer'.很难使用“答案”/“答案”的不同变体。

You can make something like that:你可以做这样的事情:

type Answer = string | boolean;
interface TestItem {
    id: string;
    answer?: Answer | Array<TestItem>;
}

const results: TestItem[] = [
        {
            "id": "test",
            "answer": "1"
        },
        {
            "id": "test_multi",
            "answer": [
                {
                    "id": "skill_1"
                },
                {
                    "id": "skill_2"
                }
            ]
        },
]

If you want to stay with 'answers', then try this:如果您想保留“答案”,请尝试以下操作:

type Answer = string | boolean;
interface TestItem {
    id: string;
    answer?: Answer;
    answers?: Array<TestItem>;
}

const results: TestItem[] = [
        {
            "id": "test",
            "answer": "1"
        },
        {
            "id": "test_multi",
            "answers": [
                {
                    "id": "skill_1"
                },
                {
                    "id": "skill_2"
                }
            ]
        },
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM