Alessandro_Russo
Alessandro_Russo

Reputation: 2231

How i can create a Typescript interface that can take also a string?

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: ['']}
]

Upvotes: 0

Views: 36

Answers (2)

user2369797
user2369797

Reputation: 36

You have to use union types:

export type Objs = Array<Obj | string>;

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075735

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

Upvotes: 1

Related Questions