typescript - TypeScript 中更严格的输入而不是“as”关键字
问题描述
请看下面的代码:
type Collections = 'Users' | 'Products' | 'Accounts';
// querying a collection
DB.collection('Users' as Collections).doc(docId).get().then(...)
// below I'm misspelling the "Users" as "User" expecting that I'll get an error. But no errors
DB.collection('User' as Collections).doc(docId).get().then(...)
如何在此处强制执行类型检查?
// one way I'm doing that is
const UsersCollectionNameKey: Collections = 'Users';
DB.collection(UsersCollectionNameKey).doc(docId).get().then(...)
这可行,但预先声明所有集合名称变量非常繁琐。我想知道我们是否有一个 typescript 关键字,is
这样它就可以强制执行类型检查?喜欢
DB.collection('Users' is Collection) // no errors
DB.collection('User' is Collection) // Err: User is not assignable to type Collection
解决方案
x as Y
语法是一种类型断言,它告诉 TypeScript 你“知道”它x
始终是 type Y
。这是为了允许您在类型系统中引入无法以其他方式推断的信息。
所以随着
DB.collection('User' as Collections)
你基本上是在告诉 TypeScript我知道 'User'
是一个Collections
,不需要检查这个- 这与你想要实现的目标相反。
相反,您需要告诉 TypeScriptDB.collection()
需要一个Collections
as 参数,您在该函数的定义中执行此操作:
public collection(name: Collections) {
// ...
}
使用此 TypeScript 将检查传递的参数是否为 type Collections
,即要么'Users'
是'Products'
要么'Accounts'
:
DB.collection('Users') // no errors
DB.collection('User') // error: Argument of type '"User"' is not assignable to parameter of type 'Collections'.
请参阅此TS 操场以获取实时示例。
如果您无法更改定义,则DB.collection()
可以编写一个包装函数作为解决方法:
function getCollection(name: Collections) {
return DB.collection(name);
}
getCollection('Users') // no errors
getCollection('User') // error: Argument of type '"User"' is not assignable to parameter of type 'Collections'.
参见TS 游乐场。
推荐阅读
- c++ - Boolean stop signal between threads
- google-cloud-platform - 停止和启动 vm 实例后 GCP 的 SSH 终端不工作
- spring - 使用 swagger api 文档和 Spring Boot 上传多个文件
- regex - 使用正则表达式删除重复字符
- python-3.x - 重新投影 geotiff 数据并使用 Python 绘图
- python - Python websocket服务器 - 发送消息
- python - 变量的值在python中没有改变
- c# - 如何根据属性名称列表仅从列表中选择一些属性?
- ruby - 如何使用 Rspec 测试 OptionParser - RSpec 选项在测试期间存储在 ARGV 数组中
- django - csrf 令牌的含义是什么?