typescript - 将数组定义为具有强制值,以及可选的其他值
问题描述
我正在尝试做这样的事情:
我有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
};
我将如何实现我想要的功能?
解决方案
您可以在元组类型中使用其余元素,如下所示:
type Teacher = {
name: string;
privileges: ["staffroom_access", ...Role[]];
}
这将为您提供所需的确切行为。
推荐阅读
- java - 由于 SocketException 导致 DTLS 握手失败,尽管套接字从未通过菜单关闭
- bash - 管道 grep 的变量值未传递到远程 ssh
- amazon-web-services - 无法使用 VPC 端点登录 ECR
- bash - 我可以同时将 cmder 用于 Git Bash 和其他命令行功能,如 dotnet、ng 等吗?
- javascript - contenteditable="false" 属性不适用于角度 10 中动态创建的跨度
- ms-word - 在重新缩放科学数字和图表时保持相同的字体大小
- image - 为什么我的图像(本地资产或下载的资产)没有在 iOS 14 上显示,而是在使用 ReactNative 0.62.x 的 Android 上显示?
- java - 将 android studio 更新到 4.2 Beta1 后,Gradle 构建失败
- laravel - 拉拉维尔。选择是否需要支点
- java - 无法使用 Java 库访问带有 Java 类的手动创建的资产文件夹