-1

New react developer, i am getting an array of objects(identifier:'' and name:'') in console, i want to know is there a way to know what kind of type am i getting (for example are 'name's boolean, string, number...?)

console.log("data",stateToProps?.map((data) => data.name) );

Sometimes at work i get to refactor others code and to add typescript, this would help me alot. any suggestions ?

const stateToProps = useSelector((state) => {
  const articles = {
    sites: state.articles.sites,
    brokers: state.siteArticles.brokers,
  };

  return articles[props.action];
});

console.log("data", stateToProps);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Are you looking for [Finding Variable Type in JavaScript](https://stackoverflow.com/q/4456336)? – VLAZ Oct 15 '21 at 20:51
  • If your data is not consistent (why would a name be a boolean?) that's something you need to fix at the API end, not on the front end. – Andy Oct 15 '21 at 20:55

3 Answers3

1

For JS types, you can write it like this :

const stateToProps = useSelector((state) => {
  const articles = {
    sites: state.articles.sites,
    brokers: state.siteArticles.brokers,
  };

  return articles[props.action];
});

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
  }
console.log(
    "data",
    mapStateToProps?.map((data) => getTypeName(data.name))
  );
0

You will have to use typeof for each one of the elements

const stateToProps = [{name: "X", value: 2}, {name: undefined, value: 2}, {name: [], value: 2}, {name: true, value: 2}]

console.log("data", stateToProps.map((element) => typeof element.name));
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 16 '21 at 03:52
0

You can use javascript's typeof operator: https://www.w3schools.com/js/js_typeof.asp

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 16 '21 at 01:32