Is there a way in TypeScript to define a function, findUser
, that can take 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 am encountering a TypeScript error on the info.user_id
because the user_id
field is not guaranteed to exist on info
.
An alternative approach would be to define the function like this:
function findUser(info: {user_id?: number; username?: string}) {
This works, but it allows passing an empty object. I want a way to check against this.
(I have a more complex scenario with 4 types of inputs. Once I solve this simpler example, I believe I can handle the more complicated one.)
So my question is: Can TypeScript support something similar to the first function definition?