Last active: 3 years ago
Generics limit function parameters
type Privilege = "user" | "admin";
type UserPrivilege = {
privilege: "user";
login: () => void;
logout: () => void;
};
type AdminPrivilege = {
privilege: "admin";
add: () => void;
delete: () => void;
};
type AdminPanelUsers = {
user: UserPrivilege;
admin: AdminPrivilege;
};
function adminPanel<T extends Privilege>(
privilege: T,
user: AdminPanelUsers[T]
) {
console.log(`${privilege} logined`);
// Type safe.
switch (user.privilege) {
case "admin":
user.add();
break;
case "user":
user.login();
break;
default:
throw new Error("Wrong type");
}
}
const normalUser: UserPrivilege = {
privilege: "user",
login: () => {},
logout: () => {}
};
const adminUser: AdminPrivilege = {
privilege: "admin",
add: () => {},
delete: () => {}
};
adminPanel("admin", adminUser);
// Will be get error.
adminPanel("admin", normalUser);