javascript - TypeScript:键入以包含任何值,但预定义集中的值除外
问题描述
是否可以有一个类型包含任何值但预定义集中的值?
type Fruit = 'Apple' | 'Banana' | 'Orange'
type NotFruit = ???
const a: NotFruit = 'Carrot'; // Compiler OK.
const b: NotFruit = 'Apple'; // Compiler ERROR.
即是否存在NotFruit
编译器根据我的代码中的注释响应的定义?
解决方案
我会回答,Typescript 绝对不可能做到这一点。该语言中的集合没有否定运算符。
不过,您可以创建一个 instanceOf 类型保护。
https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
type Fruit = "Apple" | "Orange";
function isFruit(fruit: string): fruit is Fruit {
return !(['Apple', 'Orange'].includes(fruit));
}
推荐阅读
- postgresql - 使用自动增量 ID 在 PGAdmin 3 中导入 CSV
- sql - 合并 T-SQL 中的连续行组,并对每组中的值求和
- html - Prerender.io 与 Angular Universal - 不在组件标签内呈现 HTML
- azure-devops - 板中功能的优先级
- android - 如何在 Kotlin 中管理资源?试图让 setUp 函数只运行一次,而不是在每次测试之前
- linear-regression - 为什么这个答案不正确?
- powershell - 通过批处理/powershell脚本访问dll api
- angular - 如何执行顺序服务调用?
- sql - 将行转入 Googlesql 列
- python - XML 中缺少包装器