typescript类型体操问题咨询

我想实现一种类型体操,达到从 FieldType 和 columns 中获得 Record 的能力

 

  enum FieldType {
    number,
    string,
    boolean
  }

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      type: FieldType.string,
    },
    {
      title: '邮件',
      dataIndex: 'email',
      type: FieldType.string,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      type: FieldType.number,
    },
    {
      title: '性别',
      dataIndex: 'gender',
      type: FieldType.boolean,
    },
  ];

  interface Record {
    name: string;
    email: string;
    phone: number;
    gender: boolean;
  }
    
阅读 1.6k
1 个回答
enum FieldType {
    number,
    string,
    boolean,
}

const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      type: FieldType.string,
    },
    {
      title: '邮件',
      dataIndex: 'email',
      type: FieldType.string,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      type: FieldType.number,
    },
    {
      title: '性别',
      dataIndex: 'gender',
      type: FieldType.boolean,
    },
] as const;

interface Column {
    title: string;
    dataIndex: string;
    type: FieldType;
}

type ExtractColumnType<T> = T extends FieldType.boolean
    ? boolean
    : T extends FieldType.number
        ? number
        : T extends FieldType.string
            ? string
            : never;

type Values<T> = T[keyof T];

type ExtractColumn<T> = T extends readonly (infer V)[]
    ? { -readonly [K in keyof V]: V[K]; }
    : never;

type ColumnsToRecord<T extends readonly Column[]> = {
    [P in Values<Pick<ExtractColumn<T>, "dataIndex">>]: ExtractColumnType<Extract<ExtractColumn<T>, { dataIndex: P }>["type"]>;
};

type Result = ColumnsToRecord<typeof columns>;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进