-1

I have this logic,

.switchMap((data: ISearchModalPayload | number ) => {..... }

where data is either an interface object or a number.

How can I determine the data type before I carry on with my routine?

I tried the following, from this post, but none worked:

  • if (obj instanceof C) {}
  • Object.getClass()
  • .isInstance
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
JSON
  • 1,583
  • 4
  • 31
  • 63
  • 1
    `I tried the following` - can you show exactly how you tried, because clearly, you don't have a class `C` in your code – Jaromanda X Mar 13 '18 at 22:33
  • 1
    `if (typeof data === "number") { /* do number things */ } else { /* do object things */ }`? – CRice Mar 13 '18 at 22:33
  • [how to determine variable type in javascript](https://www.google.com/search?q=how+to+determine+variable+type+in+javascript&rlz=1C5CHFA_enUS688US688&oq=how+to+determine+a+variable+type+in+jav&aqs=chrome.1.69i57j0l2.9624j0j7&sourceid=chrome&ie=UTF-8) – SaganRitual Mar 13 '18 at 22:36
  • @Xufox , it’s typescript , I apologize – JSON Mar 13 '18 at 22:53
  • Okay, please learn the difference between Java, JavaScript and TypeScript. – Sebastian Simon Mar 13 '18 at 22:56

2 Answers2

1
if (typeof obj === 'number') {
  // do stuff
} else if (typeof obj === 'object') {
  // do stuff
}
1

Are you looking for the typeof operator? E.g.

typeof obj === "number"
Koenvh
  • 79
  • 2
  • 6