i have type: type Category = 'Mfo' 'Rko'; and i have interfaces: interface Mfo { }…
- User
i have type: type Category = 'Mfo' | 'Rko';
and i have interfaces: interface Mfo { }
interface Rko { }
i want function: const value = get<T,>(category: Category): => {
}
i want get interface by category, example:
const value = get('Mfo'); value typeof Mfo
- Assistant
To achieve the desired functionality where the
getfunction returns the appropriate interface type based on the provided category, you can use TypeScript's conditional types along with the type parameterT. Here's how you can implement this:// Define the category as a type type Category = 'Mfo' | 'Rko'; // Define empty interfaces for Mfo and Rko interface Mfo { // Properties of Mfo } interface Rko { // Properties of Rko } // Type mapping from Category to Interface type CategoryToInterface<T> = T extends 'Mfo' ? Mfo : T extends 'Rko' ? Rko : never; // The get function function get<T extends Category>(category: T): CategoryToInterface<T> { // Implementation logic // Just a mock return for demonstration, needs to be replaced with actual logic if (category === 'Mfo') { return {} as CategoryToInterface<T>; } else { return {} as CategoryToInterface<T>; } } // Example usage const mfoValue = get('Mfo'); // mfoValue should be inferred as type Mfo const rkoValue = get('Rko'); // rkoValue should be inferred as type RkoExplanation:
-
Type Mapping: The
CategoryToInterfacetype maps each category string to its corresponding interface using conditional types. IfTextends'Mfo', it resolves to theMfointerface, ifTextends'Rko', it resolves to theRkointerface; otherwise, it resolves tonever. -
Function Signature: The
getfunction accepts a parameter of typeT, whereTextendsCategory. This ensures that only valid categories can be passed in. -
Return Type: The return type of the
getfunction uses theCategoryToInterfacetype to determine the type of the object being returned based on thecategoryargument. -
Usage: When calling
get('Mfo'), the return type is automatically inferred by TypeScript asMfo, and similarly, callingget('Rko')gives a return type ofRko.
Replace the mock return
{}with actual logic to fetch or create instances ofMfoorRkoas per your application needs. -