0

So in below code if i pass ancillaryProductInd as boolean code works, but when I pass it as a string, it does not work. In my understanding the below code should only work when I pass "false" string value and throw error on boolean. Any idea what is the issue here ?

main.ts

request

var rxInfos = [{
  "ancillaryProductInd": "false",
  "indexID": "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
}]


function subQuestionsHandler(rxInfos, data) {
  const subQuestionArray = [];
  rxInfos.forEach((rxInfo) => {
    const subQuestion = {
      question: []
    };
    if (rxInfo.ancillaryProductInd !== undefined && rxInfo.ancillaryProductInd === "false") {
      subQuestion.question = data;
      subQuestionArray.push(subQuestion);
    }
  });
  return subQuestionArray;
}

subQuestionsHandler(rxInfos, [{
  some data
}]);
George
  • 6,630
  • 2
  • 29
  • 36
hussain
  • 6,587
  • 18
  • 79
  • 152
  • 1
    Well nothing in that code looks like it would throw an exception. It's not an error to compare a boolean value to a string, though I would consider it a bad practice to use a string when an actual boolean would be simpler. – Pointy Dec 20 '18 at 15:32
  • @Pointy agreed but thats how are backend is expecting nothing much i can do there they want us to pass as a string – hussain Dec 20 '18 at 15:33
  • you could try this instead. check if variable is of type boolean. if (typeof variable === "boolean"){ // variable is a boolean } – JanWillem Huising Dec 20 '18 at 15:33
  • Is your code not working as expected? Do you have control over the creation of the `rxInfos` var? – WillardSolutions Dec 20 '18 at 15:33
  • If you're communicating with the server via HTTP then **everything** is a string anyway; that should not affect how your front-end logic works. – Pointy Dec 20 '18 at 15:36
  • try this one: https://stackoverflow.com/questions/44024193/typescript-string-to-boolean?rq=1 – fransyozef Dec 20 '18 at 15:36

1 Answers1

0

Your example code works as expected with a string value "false" and doesnt run the if block when a boolean is used. See my example:

var rxInfos = [
  {
    ancillaryProductInd: "false",
    indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
  },
  {
    ancillaryProductInd: false,
    indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
  }
];

function subQuestionsHandler(rxInfos, data) {
  const subQuestionArray = [];
  rxInfos.forEach(rxInfo => {
    const subQuestion = {
      question: []
    };
    if (
      rxInfo.ancillaryProductInd !== undefined &&
      rxInfo.ancillaryProductInd === "false"
    ) {
      console.log("no error");
      subQuestion.question = data;
      subQuestionArray.push(subQuestion);
    } else {
      console.log("throw error");
    }
  });
  return subQuestionArray;
}

subQuestionsHandler(rxInfos, [
  {
    test: ""
  }
]);