Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI WildChat-4.8M (AI2)

i have type: type Category = 'Mfo' 'Rko'; and i have interfaces: interface Mfo { }…

  1. 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

  2. Assistant

    To achieve the desired functionality where the get function returns the appropriate interface type based on the provided category, you can use TypeScript's conditional types along with the type parameter T. 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 Rko
    

    Explanation:

    1. Type Mapping: The CategoryToInterface type maps each category string to its corresponding interface using conditional types. If T extends 'Mfo', it resolves to the Mfo interface, if T extends 'Rko', it resolves to the Rko interface; otherwise, it resolves to never.

    2. Function Signature: The get function accepts a parameter of type T, where T extends Category. This ensures that only valid categories can be passed in.

    3. Return Type: The return type of the get function uses the CategoryToInterface type to determine the type of the object being returned based on the category argument.

    4. Usage: When calling get('Mfo'), the return type is automatically inferred by TypeScript as Mfo, and similarly, calling get('Rko') gives a return type of Rko.

    Replace the mock return {} with actual logic to fetch or create instances of Mfo or Rko as per your application needs.