K
Kysely3mo ago
lorentz

how to union two queries with json_build_object?

i would like to union two queries to get a result of type QueryA | QueryB. this query fails the type checker but the generated query seems to work as intended. is there a type hint i can provide somehow? https://kyse.link/2TBLF
Solution:
The unioned expressions need to have the same type. You used first_name in the first one an name in the second one. If both have the same property name it works. https://kyse.link/Bc300 When you use different keys, the correct type of the JSON object would be { name: string | undefined, first_name: string | undefined } but Kysely isn't able to infer it....
Jump to solution
5 Replies
Solution
koskimas
koskimas3mo ago
The unioned expressions need to have the same type. You used first_name in the first one an name in the second one. If both have the same property name it works. https://kyse.link/Bc300 When you use different keys, the correct type of the JSON object would be { name: string | undefined, first_name: string | undefined } but Kysely isn't able to infer it.
koskimas
koskimas3mo ago
This is far from optimal, but you could use $castTo to fix the type https://kyse.link/Ppshx
lorentz
lorentzOP3mo ago
alright thanks. so there is no way to make kysely type the whole result to this?
({
id: number;
details: {
first_name: string;
};
} | {
id: number;
details: {
name: string;
};
})[]
({
id: number;
details: {
first_name: string;
};
} | {
id: number;
details: {
name: string;
};
})[]
koskimas
koskimas3mo ago
No, that's not possible This is
{
id: number;
details: {
first_name: string;
} | {
name: string
};
}[]
{
id: number;
details: {
first_name: string;
} | {
name: string
};
}[]
by just casting details to that type
lorentz
lorentzOP3mo ago
ah ok! 🙇 so this in full https://kyse.link/CtZGS. now i realize what i need is really a discriminated union type though, so something closer to this https://kyse.link/4Zw87. the result gets the correct type now
const rows: ({
id: number;
type: "person";
details: {
first_name: string;
};
} | {
id: number;
type: "pet";
details: {
name: string;
};
})[]
const rows: ({
id: number;
type: "person";
details: {
first_name: string;
};
} | {
id: number;
type: "pet";
details: {
name: string;
};
})[]
but then back to Types of property 'details' are incompatible. where union is not happy. is there any way to just convince the union that all is good? 😄 don't mind explicitly casting anything at this point ok i think i have something https://kyse.link/xpMTf. perhaps not ideal, but works. thank you very much for the help!
Want results from more Discord servers?
Add your server