Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 将数组定义为具有强制值以及其他可选值_Typescript - Fatal编程技术网

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

这会给你想要的准确行为。

我也不会!必须查找:)