When you use the x as Y
syntax in TypeScript, it is considered a form of type assertion. This syntax essentially informs TypeScript that you are certain x
will always be of type Y
. It provides a way to convey additional information to the type system that may not be deduced automatically.
For example,
DB.collection('User' as Collections)
essentially tells TypeScript "I'm absolutely sure that 'User'
belongs to Collections
, no need for verification", which goes against the intended purpose.
Instead, the correct approach is to specify in the function definition itself what type should be expected for the parameter passed to DB.collection()
:
public collection(name: Collections) {
// ...
}
By doing this, TypeScript will validate that the supplied parameter is indeed of type Collections
, such as either 'Users'
, 'Products'
, or 'Accounts'
:
DB.collection('Users') // no errors
DB.collection('User') // error: Argument of type '"User"' is not assignable to parameter of type 'Collections'.
You can check out this TS playground for a practical demonstration.
If modifying the definition of DB.collection()
is not an option, you might consider creating a wrapper function as a temporary fix:
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'.
Explore more on this in the TS playground.