Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created January 12, 2021 21:48
Show Gist options
  • Save ryanflorence/84114f38083a973e006787b9879886eb to your computer and use it in GitHub Desktop.
Save ryanflorence/84114f38083a973e006787b9879886eb to your computer and use it in GitHub Desktop.
generic generics?
// My DB has multiple collections (tables), they can extend
// this since the only difference is the data an collection,
// they're passed in as generics
export interface Record<TData, TCollection> {
data: TData;
ref: {
collection: {
id: TCollection;
};
id: string;
ts: number;
};
}
// for example, here are posts
interface PostRecord
extends Record<
{
title: string;
published: boolean;
body: string;
},
"posts"
> {}
// and sessions
interface SessionRecord
extends Record<
{
id: string;
values: { [key: string]: string };
},
"sessions"
> {}
// how do I tell this function it's getting a generic Record?
export function serializeRecord<
TRecord extends Record<???, ???>
>(record: TRecord): TRecord {
let { data, ref } = record;
return {
data,
ref: {
id: ref.id,
ts: ref.ts,
collection: {
id: ref.collection.id,
},
},
};
}
// is there some way to infer or access `TRecord`'s generic TData and TCollection?
@Paduado
Copy link

Paduado commented Jan 13, 2021

Why not:

export function serializeRecord<
  T extends Record<any, string>
>(record: T): T {
  let { data, ref } = record;
  return {
    data,
    ref: {
      id: ref.id,
      ts: ref.ts,
      collection: {
        id: ref.collection.id,
      },
    },
  } as T;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment