How to type either

Quick question. I have an object I'm passing as a parameter. It has the shape
{id: number, name: string, foo: Partial<SomeObject>}
{id: number, name: string, foo: Partial<SomeObject>}
I need either or both id and name, and I require foo. How would I go about typing this?
5 Replies
Amos
Amos•3y ago
type SomeObject = Record<string, string>;

type OneOrTheOther =
| { id: number; foo: Partial<SomeObject> }
| { name: string; foo: Partial<SomeObject> }
| { id: number; name: string; foo: Partial<SomeObject> };

const MyThing: OneOrTheOther = { foo: {}, id: 1 };
type SomeObject = Record<string, string>;

type OneOrTheOther =
| { id: number; foo: Partial<SomeObject> }
| { name: string; foo: Partial<SomeObject> }
| { id: number; name: string; foo: Partial<SomeObject> };

const MyThing: OneOrTheOther = { foo: {}, id: 1 };
Does this work?
benten
benten•3y ago
It does, idk why I didn't think of explicitly unioning the three possible versions thanks legend Hmm actually it's not It's telling me that id and name don't exist on type mything when i use it as a param hmm this works apparently
type TUpdateMeal =
| { id: number; name?: string; newState: Partial<TMeal> }
| { name: string; id?: number; newState: Partial<TMeal> }
type TUpdateMeal =
| { id: number; name?: string; newState: Partial<TMeal> }
| { name: string; id?: number; newState: Partial<TMeal> }
thanks for the help you got me 95% of the way there
Amos
Amos•3y ago
Can you do name?: never and id?: never to make it even more explicit (I had that before, but removed it since I thought it worked w/o 😓)
benten
benten•3y ago
Would never imply it can't be two at once?
Amos
Amos•3y ago
Yeah you'd have to have the 3rd one saying it can be both
Want results from more Discord servers?
Add your server