Home > Software design >  How to define a list of optional strings as property of an interface in Typescript
How to define a list of optional strings as property of an interface in Typescript

Time:08-31

I would like to have a property on an interface, interests for example, which is a list of one or more pre-defined interests.

For example, the interface would look something like:


// User Data Model
export default interface User {
    uid: String;
    email: string;
    username: string;
    firstName?: String;
    lastName?: String;
    interests: partial<Interests>;
}

// Interests data model
type Interests = ['swimming', 'running', 'movies', 'hiking'];

And the implementation could be as follows:

const user: User = {
    uid: "123abc",
    email: "[email protected]",
    username: "soapMctavish",
    firstName: "Joe",
    lastName: "Soap",
    interests: ["swimming", "movies"]
}

The goal is to avoid defining interests as follows:

export default interface User {
    ...
    interests: "Movies" | "Swimming" | "Hiking" | ...etc;
}

And to have the ability to define 1 through n interests per user.

CodePudding user response:

You want to somehow get the union

'swimming' | 'running' | 'movies' | 'hiking'

from

type Interests = ['swimming', 'running', 'movies', 'hiking'];

You can achieve that by indexing into Interests with number:

Interests[number] // 'swimming' | 'running' | 'movies' | 'hiking'

Then you wrap this union into an array for the desired result:

Interests[number][] // ('swimming' | 'running' | 'movies' | 'hiking')[]
  • Related