User object can have different types of social media accounts (email
, google
, twitter
), and each type stores the username in a unique key (address
for email, name
for Google, and username
for X (formerly known as Twitter)). I am attempting to dynamically retrieve the username for a given social type by passing the type as a parameter to a function.
interface email {
address: string;
}
interface google {
name: string;
}
interface twitter {
username: string;
}
interface User {
email?: email;
google?: google;
twitter?: twitter;
}
function getUsername(social: "email" | "google" | "twitter", user: User) {
const userUsernames = {
email: "address",
google: "name",
twitter: "username",
} as const;
const socialAccount = user[social];
const username = socialAccount ? socialAccount[userUsernames[social]] : null;
return username
}
But I am getting
Element implicitly has an ‘any’ type because expression of type ‘”address” | “name” | “username”‘ can’t be used to index type ’email | google | twitter’
I am aware that I could use if statements or a switch case to handle type-specific property access, but I am exploring if there’s a way to achieve this dynamically in TypeScript without explicitly checking each type. How can this be done while ensuring type safety?
estarossa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1