首页 > 解决方案 > 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

标签: typescript

解决方案


x as Y语法是一种类型断言,它告诉 TypeScript 你“知道”它x始终是 type Y。这是为了允许您在类型系统中引入无法以其他方式推断的信息。

所以随着

DB.collection('User' as Collections)

你基本上是在告诉 TypeScript知道 'User'是一个Collections,不需要检查这个- 这与你想要实现的目标相反。

相反,您需要告诉 TypeScriptDB.collection()需要一个Collectionsas 参数,您在该函数的定义中执行此操作:

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 游乐场


推荐阅读