RobertK
RobertK

Reputation: 27

Array of allowed values

Say I have the following two types:

type OrganizationType = 'NGO' | 'Business';
type Organization = {
    name: string,
    type: OrganizationType,
    weekdaysOpen: string[],
};

How can I define weekdaysOpen such that its elements are restricted to any (or none) of some predefined values? In this case they would be:

// Allowed elements in weekdaysOpen
'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'

Bonus if each allowed value can only appear once.

Upvotes: 0

Views: 417

Answers (2)

pzaenger
pzaenger

Reputation: 11984

You could use a Set to allow only unique values:

type WeekDay = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';

type Organization = {
  ...
  weekdaysOpen: Set<WeekDay>
};

Upvotes: 1

Viet Dinh
Viet Dinh

Reputation: 1961

You can try with:

type OrganizationType = 'NGO' | 'Business';
type WeekDay = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
type Organization = {
    name: string,
    type: OrganizationType,
    weekdaysOpen: WeekDay[],
};

Upvotes: 2

Related Questions