-2

Typeof has some really basic functionality:

typeof in JavaScript only returns basic info

typeof "Hello World" would return string.

typeof [1,2,3] would return object

I'm looking for a function that I can input like [1,"string", {property: "object"}] and it would return Array<number | string | object> or something like that.

  • you could use a replacer function w/json.stringify to iterate and return types – dandavis Apr 29 '20 at 03:58
  • Can you expand on what you mean by "*typescript types*"? Maybe point to the relevant TypeScript documentation for what you're referring to? – esqew Apr 29 '20 at 04:13

1 Answers1

0

You could roll your own that iterates over each element and determines if it's a distinct typeof value, joining the result array into the format you defined:

var improvedTypeOf = (obj) => {
  if (!obj instanceof Array) return typeof obj;
  return "Array<" + obj.reduce((acc, ele) => {
    if (!acc.includes(typeof ele)) acc.push(typeof ele);
    return acc;
  }, []).join(" | ") + ">";
}

console.log(improvedTypeOf([1,"string", {property: "object"}, ]));
esqew
  • 42,425
  • 27
  • 92
  • 132
  • This won't work, as there are endless possibilities. What if there is a custom class in the array? I wouldn't want just "object" as the type for the class. I was really just looking to see if there was a lib out there that could work. I'll mark your answer as checked since I don't think there is a good lib out there. – Bop It Freak Apr 29 '20 at 04:26
  • In that case, instead of getting the `typeof ele` you might consider using its constructor name instead: `ele.constructor.name`. See also: [this related SO answer](https://stackoverflow.com/a/10314492/269970) – esqew Apr 29 '20 at 04:30