1

I'm working with a library which defines the following interfaces:

LocalUser {
  data {
    value: LocalDataValue
  },
  ...various other methods etc...
}
RemoteUser {
  data {
    value: RemoteDataValue
  },
  ...various other methods etc...
}

Then it gives me a User which is defined like this (I can work out which type of user it is based on how it was obtained, but there doesn't seem to be a way to actually pass that information on):

User {
  value: LocalUser|RemoteUser
}

because for the vast majority of my code it doesn't matter. However, at one point I need to know whether I'm dealing with a LocalUser, because I only want to do a particular operation on LocalUsers. Is there a way to know whether a LocalUser is a RemoteUser or a LocalUser?

I can't find anywhere in the documentation which tells me what the difference is between them, though I know that some methods only appear on LocalUser and not on RemoteUser (eg I can do localUser.enable() but remoteUser.enable() doesn't work).

Is there a way to do something like this:

if(myUnknownUser isInstanceOf (LocalUser)) { doSomething() }

or a better way to handle this?

1 Answer 1

2

For such cases you should use typeguards

Consider this example:


type LocalUser = {
  tag: 'LocalUser';
  name: 'John'
}

type RemoteUser = {
  tag: 'RemoteUser';
  name: 'David'
}
type User = LocalUser | RemoteUser

// typeguard
const isLocal = (user: User): user is LocalUser => user.tag === 'LocalUser'

// typeguard
const isRemote = (user: User): user is RemoteUser => user.tag === 'RemoteUser'

declare var user: User;

if (isLocal(user)) {
  const x = user // LocalUser
}

if (isRemote(user)) {
  const x = user // RemoteUser
}

It is up to you how you will implement typeguard

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you - I hadn't heard of typeguards, but I'll go and do some research now. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.