typescript - 键入“除...之外的所有可能的字符串值”
问题描述
是否可以定义一种类型,除了少数指定的字符串值之外,每个字符串值都被分配?我想按照这个(非编译)示例的方式表达一些东西:
type ReservedNames = "this" | "that"
type FooName = string - ReservedNames;
const f1 : FooName = "This" // Works
const f2 : FooName = "this" // Should error
解决方案
这个问题没有通用的解决方案,因为没有办法在打字稿类型系统中表达字符串可以是除列表之外的任何值这一事实。(有人可能认为条件类型Exclude<string, ReservedNames>
会起作用,但它不会,它只是返回到 string)。
作为一种解决方法,如果我们有一个函数,并且我们特别希望不允许传入某些常量,我们可以使用条件类型来检查ReservedNames
,如果传入的参数是ReservedNames
输入参数,那么输入参数是这样的:实际上不可能满足(使用交集类型)。
type ReservedNames = "this" | "that"
type FooName = Exclude<string, ReservedNames>;
const f1 : FooName = "This" // Works
const f2 : FooName = "this" // One might expect this to work but IT DOES NOT as FooName is just evaluates to string
function withName<T extends string>(v: T & (T extends ReservedNames ? "Value is reserved!": {})) {
return v;
}
withName("this"); // Type '"this"' is not assignable to type '"Value is reserved!"'.
withName("This") // ok
推荐阅读
- android - 无法在 Android Studio 中点击 XML 预览
- branch.io - 我们无法访问中国的 branch.io
- node.js - 面对此错误“加载资源失败:服务器响应状态为 404(未找到)”在 web
- sql - SQL 事务归因
- ios - 如何单击 UITabBarItem 并显示新的 ViewController?
- mysql - 错误 1932 (42S02):引擎中不存在表 'xxx.wp_users'
- mysql - SQL - 从几个连接中获取表的行数
- python-3.x - 使用来自另一个类变量的信息更新 ScrolledText 框
- c# - 学生信息的数据绑定
- dart - 什么时候需要对flutter(dart)中的变量使用final