0

I need to create an interface that permit to have an array of objects and strings.

For example:

const array = [
 '',
 {id: '', labels: ['']}
]

I've tried with:

export interface Obj{
  id: string;
  label: string[];
}

export interface Objs extends Array<Obj> {
}

But this don't permit strings so this return an error:

const array: Objs = [
 '',
 {id: '', labels: ['']}
]

2 Answers 2

2

You have to use union types:

export type Objs = Array<Obj | string>;
Sign up to request clarification or add additional context in comments.

Comments

1

If the entries in the array can be either strings or objects in the form {id: string; labels: string[]}, you can use a union type:

export type Obj = string | {id: string; labels: string[]};
const array: Obj[] = [
    "",
    {id: "", labels: [""]}
];

Playground Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.