首页 > 解决方案 > 将数组定义为具有强制值,以及可选的其他值

问题描述

我正在尝试做这样的事情:

我有Student类型和Teacher类型,它们是相似的,除了所有的老师总是有"staffroom_access"特权。学生可以选择拥有此特权。

我试图用这条线来做这件事:

privileges: Role[] extends ["staffroom_access"]

但这给了我:

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

完整代码:

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 
}; 

我将如何实现我想要的功能?

标签: typescript

解决方案


您可以在元组类型中使用其余元素,如下所示:

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

这将为您提供所需的确切行为。


推荐阅读