dwjohnston
dwjohnston

Reputation: 11813

Define an array as having a mandatory value, plus optional others

I am trying to do something like this:

I have a Student type and Teacher type, they are similar, except that all teachers always have the "staffroom_access" privilege. Students can optionally have this privilege.

I've tried to do this as below with this line:

privileges: Role[] extends ["staffroom_access"]

But this gives me:

Property 'privileges' of exported interface has or is using private name ''.(4033)

Full code:

type Role = "staffroom_access" | "sportsroom_access"; 

type Teacher = {
    name: string; 
    privileges: Role[] extends ["staffroom_access"]; //Property 'privileges' of exported interface has or is using private name ''.(4033)
}

type Student = {
    name: string; 
    privileges: Role[]; 
}

const mrJones: Teacher = {
    name: "Mr Jones",
    privileges: [] //Should error
}; 

const mrSmith: Teacher = {
    name: "Mr Smith",
    privileges: ["staffroom_access"] //Should be Ok 
}; 

How would I achieve the functionality that I want?

Upvotes: 1

Views: 49

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

You can use rest elements in tuple types as follows:

type Teacher = {
    name: string; 
    privileges: ["staffroom_access", ...Role[]];
}

This will give you the exact behavior you want.

Upvotes: 2

Related Questions