Skip to main content

TypeScript Typing & Generics

MiftahDB is fully typed with TypeScript, allowing you to leverage TypeScript's static type checking and type inference. You can use generic types to specify the type of values stored and retrieved from the database.

When retrieving values from MiftahDB, you can define the type of the stored value for better type safety:

type User = {
name: string;
age: number;
};

// Set a value with TypeScript typing
db.set<User>("user:1234", {
name: "Ahmad",
age: 15,
});

// Retrieve the value with TypeScript typing
const getResult = db.get<User>("user:1234");
if (getResult.success) {
console.log(`User: ${getResult.data.name}`);
} else {
console.log(getResult.error.message);
}

// Multi-Set a value with TypeScript typing
db.multiSet<User>([
{
key: "user:2345",
value: { name: "Ahmad", age: 15 },
expiresAt: new Date("2025-12-31"),
},
{ key: "user:7890", value: { name: "Mohamed", age: 25 } },
]);

// Multi-Get a value with TypeScript typing
const multiGetResult = db.multiGet<User>(["user:2345", "user:7890"]);
if (multiGetResult.success) {
console.log(multiGetResult.data[0].age);
} else {
console.log(multiGetResult.error.message);
}