PaulB
PaulB

Reputation: 33

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.

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.

How can I write the type for "this array can contain this object AND/OR this object"?

Upvotes: 2

Views: 1267

Answers (2)

Alex Bagatka
Alex Bagatka

Reputation: 56

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"
                }
            ]
        },
]

Upvotes: 0

ShamPooSham
ShamPooSham

Reputation: 2379

You can use parentheses like this:

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

Upvotes: 2

Related Questions