Generic & intersection

I'm looking to have a helper arkWithMetadata, which basically takes a base type and add { metadata: { id: <id> }} I wanted to write this :
export const arkWithMetadata = type(
'<doc extends Record<string, unknown>, id extends string>',
"{ metadata: { id: 'id' } & doc"
);
export const arkWithMetadata = type(
'<doc extends Record<string, unknown>, id extends string>',
"{ metadata: { id: 'id' } & doc"
);
But it doesn't work. I want to retain both types doc and id. Is there a way to do that ? I also tried to write a function :
export function arkWithMetadata<
const Doc extends Record<string, unknown>,
const Id extends string,
>(doc: Type<Doc>, id: Type<Id>) {
return type(doc as any).and(id as any) as Type<
Doc & { metadata: { id: Id; cas: string } }
>;
}
export function arkWithMetadata<
const Doc extends Record<string, unknown>,
const Id extends string,
>(doc: Type<Doc>, id: Type<Id>) {
return type(doc as any).and(id as any) as Type<
Doc & { metadata: { id: Id; cas: string } }
>;
}
But it doesn't work either 🤷‍♂️ PS: I'm using v2.0.0-rc.18
12 Replies
Dimava
Dimava2mo ago
Type deos have withMetadata or smth
JesusTheHun
JesusTheHunOP2mo ago
@Dimava of course not, that's just some business name I just want a generic type that can be expressed in the form of an intersection In my case it's a validator named arkWithMetadata that takes two arguments, a Type representing some kind of record, and a Type that extends string. The TypeScript equivalent is :
type WithMetadata<T extends Record<string, unknown>, ID extends string> = T & {
metadata: {
id: ID;
cas: string;
};
};
type WithMetadata<T extends Record<string, unknown>, ID extends string> = T & {
metadata: {
id: ID;
cas: string;
};
};
Dimava
Dimava2mo ago
You are looking for .merge I guess
JesusTheHun
JesusTheHunOP2mo ago
how does that play with a generic ?
Dimava
Dimava2mo ago
const WithMetadata = generic('T', 'M')([ 'T', '&', { metadata: 'M' } ])
const WithMetadata = generic('T', 'M')([ 'T', '&', { metadata: 'M' } ])
I mean '.and' does not work as & on objects iirc Or does it
JesusTheHun
JesusTheHunOP2mo ago
I assumed it does too
Dimava
Dimava2mo ago
Anyways does this work?
JesusTheHun
JesusTheHunOP2mo ago
Btw, is there an equivalent for merge ? Because an intersection is not the same, although it works for me here Let me try It works perfectly ! You are a beast 😄 do you want me to open another topic for my question about merge vs & ?
Dimava
Dimava2mo ago
Check the docs maaaaaybe its there idk Otherwise yes
JesusTheHun
JesusTheHunOP2mo ago
are you the author of the lib ?
Dimava
Dimava2mo ago
Nah I'm contributor Has been hitting every pipe edge case bug is the last month
JesusTheHun
JesusTheHunOP2mo ago
oh yeah, I've seen the issues on GH ^^ nope, nothing about merge
Want results from more Discord servers?
Add your server