1

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?

3 Answers 3

1

You need to define both alternatives as type:

  type UserInfo = { user_id: number; username?: string; } | { user_id?: number; username: string };

  function findUser(info: UserInfo ) {

Note that this way will allow providing both user_id and username. If this is not desired, you can use never type:

  type UserInfo = { user_id: number; username?: never; } | { user_id?: never; username: string };

  function findUser(info: UserInfo ) {
Sign up to request clarification or add additional context in comments.

Comments

1

you can use interfaces or a fast way like this

const findUser: { (name: string) : void; (Id: number): void; } = (value: string | number): void => {
if (typeof value === typeof 'string') { console.log("find by name") }

Comments

0

I would do it that way

interface PropsName {
  userName: string
  userId?: string
}

interface PropsID {
  userId: string
  userName?: string
}

function findUser(info: PropsName | PropsID) {
  if (info.userId) {
    
  }
  if (info.userName) {

  }
}

playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.