export interface IUser {
_id?: ObjectId
id: idType;
username: string
email: string
password: string
profilePic?: string
contributions?: number
rate?: number
bio?: string
}```
I would like to update the definition of the id field based on the value of the DB_TYPE environment variable. If DB_TYPE is set to 'sql', the type of the id field should be string. Otherwise, if DB_TYPE is set to 'mongodb' or is not defined, the type of the id field should be never. How can I achieve this?
#Conditional Type
13 messages · Page 1 of 1 (latest)
not possible
environment variables are dynmaic and can't be known at compile time
I suggest creating different variations of that IUser type
and create a union for all variations
then use a type predicate function to pick the right type where you need it
also, on a sidenote, it's not a common thing to name your interfafes with a leading I
just use the "normal" name directly
Thanks for your clarification ..
can u show me the code
Preview:```ts
import {} from "node:process"
import {ObjectId} from "mongodb"
////////////////////// The types for the application
interface SQLUser extends PartialUser {
id: string
}
interface NoSQLUser extends PartialUser {
_id?: ObjectId
}
interface
...```
You can choose specific lines to embed by selecting them before copying the link.
@sick umbra
but tbh, I probably wounld't do that
the id part of your type is specific to the db you use
and the model (classes and types) of your app shouldn't have to deal with that
you should create types that work for any kind of db, and only deal with those spefici fields when saving of retrieving data from or to the database
const user: IUser = {
id: crypto.randomUUID(), // generate uuid if dbType = sql
username,
email,
password: hashPassword(password!),
bio,
socialLinks,
interests,
profilePic,
activity: {
problems: [],
solutions: [],
reacts: [],
},
createdAt: new Date(),
updatedAt: new Date(),
}
This is the structure of user