I have a typescript function, findUser that I would like to have as inputs either a username (as a string) or a user_id as a number.
function findUser(info: { user_id: number } | { username: string}) { if (info.user_id) { } if (info.username) { } } I'm getting the typescript error on the info.user_id clearly because the user_id field it is not guaranteed to exist on info.
I realize an alternative way to do this is to define the function as
function findUser(info: { user_id?: number; username?: string}) { and then it works, however clearly you can pass in an empty object and it would be nice to have a way to check against this.
(Also, I have a more-complicated structure with 4 types of inputs. And I think if I solve this simpler example, I can determine the more complicated one.)
My question: is there a way in typescript to do something like the first function definition?