Typescript 将数组定义为具有强制值以及其他可选值
我正在尝试这样做: 我有一个Typescript 将数组定义为具有强制值以及其他可选值,typescript,Typescript,我正在尝试这样做: 我有一个Student类型和Teacher类型,它们类似,只是所有教师都有“staffroom\u access”特权。学生可以选择拥有此特权 我试着用这句话做如下的事情: privileges: Role[] extends ["staffroom_access"] 但这给了我: Property 'privileges' of exported interface has or is using private name ''.(4033) 完整代码: type Ro
Student
类型和Teacher
类型,它们类似,只是所有教师都有“staffroom\u 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
};
我将如何实现我想要的功能 可以在元组类型中使用rest元素,如下所示:
type Teacher = {
name: string;
privileges: ["staffroom_access", ...Role[]];
}
这会给你想要的准确行为。我也不会!必须查找:)