【问题标题】:Getting deep typescript type in a less verbose way以不那么冗长的方式获取深层打字稿类型
【发布时间】:2023-02-15 21:22:00
【问题描述】:

我想抽象出一个类型的深层路径。

就在示例数据类型: (由 Supabase 生成的类型)

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

什么是 uinder Row 是我试图分配给 varialbe 的数据结构。现在的方法是

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

有没有办法以某种方式抽象它?

理想的抽象是:

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

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

一般来说,只能找到一些关于泛型的信息并限制它们,但似乎还没有找到一种方法来实现我正在寻找的东西。

【问题讨论】:

    标签: typescript types supabase supabase-database


    【解决方案1】:

    好吧,ChatGPT 真是个了不起的家伙。只需复制粘贴此问题即可获得有效答案?

    这就是我所拥有的:

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

    TableSelector 类型将表名作为类型参数(在本例中为 'profiles' 表),并返回该表的行类型。使用此类型选择器函数,您可以通过将表名作为类型参数传递,轻松地为 Database 类型中的任何表选择行类型。

    【讨论】:

      猜你喜欢
      • 2010-09-09
      • 2017-02-23
      • 2020-05-09
      • 2017-06-22
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      相关资源
      最近更新 更多