Search code examples
typescripttypessupabasesupabase-database

Getting deep typescript type in a less verbose way


I would like to abstract deep path to a type.

Right onto example data type: (type generated by Supabase)

export interface Database {
    public: {
        Tables: {
            profiles: {
                Row: {
                    email: string;
                    full_name: string | null;
                    id: string;
                    is_complete: boolean;
                };
                Insert: {...};
                Update: {...};
            },
            project: {...},
            service: {...},
            ...
        },
        Views: {...},
        ...
    };
};

What is uinder Row is my data structure I'm trying to assign to a varialbe. The way to go right now is

const profiles: Database['public']['Tables']['profiles']['Row']

Is there a way to abstract it somehow?

Ideal abstraction would be:

const profiles: Profiles // Pointing to Database['public']['Tables']['profiles']['Row']

const profiles: SomeTypeSelectFunction['profiles'] // Could also do

In general could only find some info about generics and constraining them, but can't yet seem to find a way to achieve this what I'm looking for.


Solution

  • Well, ChatGPT is one hell of a fellow. Just copy pasted this question and got a working answer with an concise and easy to understand explanation of why it works 👏

    This is what I've got:

    type TableSelector<T extends keyof Database['public']['Tables']> = Database['public']['Tables'][T]['Row'];
    
    const profiles: TableSelector<'profiles'>;
    

    The TableSelector type takes a table name as a type argument (in this case, the 'profiles' table), and returns the row type for that table. With this type selector function, you can easily select the row type for any table in the Database type by passing the table name as a type argument.


    I've validated that answer is working, and hope people will use upvote responsibly as described in Stack Overflow GPT Policy to further strengthen the accuracy of knowledge base of the community.