'How to differentiate between Blob, Object and String?

Lets say some function can return Blob, String or plain Object, depending on the use case. After the value is returned I want to implement different code for each type. How can I tell them apart?

For simplification I commented the 3 options that can return from the manage function, but this is the way I manage it right now:

const manage = () => {
    
  return new Blob([JSON.stringify({ myKey: 'myValue'})], { type: 'application/json' });
  
  // return { error: 'my error msg' };
  
  // return 'lets say this is base64 string';
};

const result: Blob | { error: string } | string = manage();

switch(Object.prototype.toString.call(result)) {
    case "[object Blob]":
    console.log('Blob case runs...');
    break;
  case "[object String]":
    console.log('String case runs...');
    break;
  case "[object Object]":
    console.log('Object case runs...');
    break;
  default: console.log('Default case runs...');
 };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Obviously I am not happy with the "Object.prototype.toString.call" solution. Also some answers suggested to use the "instance of" operator, but this is also not a reliable option in my situation.

Can someone point me in a better direction?



Solution 1:[1]

you can just return the type of data and the data in the manage function

const manage = () => {
    
  return {
    type: "Bolb",
    data: new Blob([JSON.stringify({ myKey: 'myValue'})], { type: 'application/json' });
  }
   return {type: "error", error: 'my error msg' };
  
   return {type: "string", message: 'lets say this is base64 string'};
};

const result: Object = manage();

switch(result.type) {
    case "Bolb":
    console.log('Blob case runs...');
    break;
  case "string":
    console.log('String case runs...');
    break;
  case "error":
    console.log('Object case runs...');
    break;
  default: console.log('Default case runs...');
 };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad Esam