The concept might seem complex, but here's the gist of it.
I have a User
interface that may or may not contain certain properties depending on where it is fetched from. For example, there are optional properties like role
and client_details
.
export interface User {
id: string;
first_name: string;
last_name: string;
email: string;
// -- One of these is undefined based on fetch location
role?: Role;
client_details?: ClientDetails;
}
The current approach works, but having an undefined value every time isn't ideal. It would be cleaner if I could do this:
export interface User<ExtraType = Role | ClientDetails> {
id: string;
first_name: string;
last_name: string;
email: string;
// -- Using dynamic property names for a cleaner solution
[ExtraType === Role ? 'role' : 'client_details']: ExtraType;
}
However, this method throws several errors, particularly
A computed property name cannot reference a type parameter from its containing type
.
While I know I can simply create a static property called extra
and use it consistently, I wanted the property name to be more intuitive. Is there a way to achieve this? Thank you!