TypeScript gives error if instead of returning value throws Error












0















I have this function:



public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
const id = obj.id;
this.objectCollector.forEach( object => {
if(object.getID() === id){
return object;
}
});

throw new Error(`Scene.getObject(). Object ${id} not found`);
}


And I get the following ts error:




Not all code paths return a value.




That's true, because object.id must not be in objectCollector Array, in which case I throw an Error. How could I make this work? I've tried doing




public getObject(obj:IObjectsCommonJSON): ObjectsCommon | void




But it does not work either










share|improve this question























  • Try return this.objectCollector.......

    – Banujan Balendrakumar
    Nov 21 '18 at 17:48











  • return in forEach?

    – epascarello
    Nov 21 '18 at 18:06






  • 1





    Why are you not using find() ?

    – epascarello
    Nov 21 '18 at 18:07
















0















I have this function:



public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
const id = obj.id;
this.objectCollector.forEach( object => {
if(object.getID() === id){
return object;
}
});

throw new Error(`Scene.getObject(). Object ${id} not found`);
}


And I get the following ts error:




Not all code paths return a value.




That's true, because object.id must not be in objectCollector Array, in which case I throw an Error. How could I make this work? I've tried doing




public getObject(obj:IObjectsCommonJSON): ObjectsCommon | void




But it does not work either










share|improve this question























  • Try return this.objectCollector.......

    – Banujan Balendrakumar
    Nov 21 '18 at 17:48











  • return in forEach?

    – epascarello
    Nov 21 '18 at 18:06






  • 1





    Why are you not using find() ?

    – epascarello
    Nov 21 '18 at 18:07














0












0








0








I have this function:



public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
const id = obj.id;
this.objectCollector.forEach( object => {
if(object.getID() === id){
return object;
}
});

throw new Error(`Scene.getObject(). Object ${id} not found`);
}


And I get the following ts error:




Not all code paths return a value.




That's true, because object.id must not be in objectCollector Array, in which case I throw an Error. How could I make this work? I've tried doing




public getObject(obj:IObjectsCommonJSON): ObjectsCommon | void




But it does not work either










share|improve this question














I have this function:



public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
const id = obj.id;
this.objectCollector.forEach( object => {
if(object.getID() === id){
return object;
}
});

throw new Error(`Scene.getObject(). Object ${id} not found`);
}


And I get the following ts error:




Not all code paths return a value.




That's true, because object.id must not be in objectCollector Array, in which case I throw an Error. How could I make this work? I've tried doing




public getObject(obj:IObjectsCommonJSON): ObjectsCommon | void




But it does not work either







javascript function typescript typescript-typings






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 17:39









Alberto ValeroAlberto Valero

486




486













  • Try return this.objectCollector.......

    – Banujan Balendrakumar
    Nov 21 '18 at 17:48











  • return in forEach?

    – epascarello
    Nov 21 '18 at 18:06






  • 1





    Why are you not using find() ?

    – epascarello
    Nov 21 '18 at 18:07



















  • Try return this.objectCollector.......

    – Banujan Balendrakumar
    Nov 21 '18 at 17:48











  • return in forEach?

    – epascarello
    Nov 21 '18 at 18:06






  • 1





    Why are you not using find() ?

    – epascarello
    Nov 21 '18 at 18:07

















Try return this.objectCollector.......

– Banujan Balendrakumar
Nov 21 '18 at 17:48





Try return this.objectCollector.......

– Banujan Balendrakumar
Nov 21 '18 at 17:48













return in forEach?

– epascarello
Nov 21 '18 at 18:06





return in forEach?

– epascarello
Nov 21 '18 at 18:06




1




1





Why are you not using find() ?

– epascarello
Nov 21 '18 at 18:07





Why are you not using find() ?

– epascarello
Nov 21 '18 at 18:07












2 Answers
2






active

oldest

votes


















1














The error is inside the callback to forEach(), not on the getObject() call. Note that even though you are using an arrow function, it's still a function. And the return inside the callback is returning from the arrow function, not from getObject(). Note that for arrow functions, x => {return y} is equivalent to x => y. There's no way to return from an outer function from inside an arrow function.



So this is your function:



object => {
if(object.getID() === id){
return object;
}
}


And the compiler (if you've enabled --noImplicitReturns) notices that this function only sometimes returns a value, and so it complains.



Of course, forEach() doesn't care about the return value of its callback, and that wasn't your intent anyway. The fix is to do what others have suggested... use find() instead of forEach(): ... this.objectCollector.find(o => o.getID()===id) ... Or use a for loop:



for (let object of this.objectCollector) {
if (object.getID() === id) {
return object; // no callback, this returns from the getObject function.
}
}


Hope that helps; good luck!






share|improve this answer
























  • Thanks for the explanation @jcalz . Now it's clear!!

    – Alberto Valero
    Nov 21 '18 at 18:46



















1














I would use find() and add if check to throw the error.



public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
const id = obj.id;
const item = this.objectCollector.find(object => object.getID() === id);
if (!item) {
throw new Error(`Scene.getObject(). Object ${id} not found`);
}
return item;
}





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417766%2ftypescript-gives-error-if-instead-of-returning-value-throws-error%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The error is inside the callback to forEach(), not on the getObject() call. Note that even though you are using an arrow function, it's still a function. And the return inside the callback is returning from the arrow function, not from getObject(). Note that for arrow functions, x => {return y} is equivalent to x => y. There's no way to return from an outer function from inside an arrow function.



    So this is your function:



    object => {
    if(object.getID() === id){
    return object;
    }
    }


    And the compiler (if you've enabled --noImplicitReturns) notices that this function only sometimes returns a value, and so it complains.



    Of course, forEach() doesn't care about the return value of its callback, and that wasn't your intent anyway. The fix is to do what others have suggested... use find() instead of forEach(): ... this.objectCollector.find(o => o.getID()===id) ... Or use a for loop:



    for (let object of this.objectCollector) {
    if (object.getID() === id) {
    return object; // no callback, this returns from the getObject function.
    }
    }


    Hope that helps; good luck!






    share|improve this answer
























    • Thanks for the explanation @jcalz . Now it's clear!!

      – Alberto Valero
      Nov 21 '18 at 18:46
















    1














    The error is inside the callback to forEach(), not on the getObject() call. Note that even though you are using an arrow function, it's still a function. And the return inside the callback is returning from the arrow function, not from getObject(). Note that for arrow functions, x => {return y} is equivalent to x => y. There's no way to return from an outer function from inside an arrow function.



    So this is your function:



    object => {
    if(object.getID() === id){
    return object;
    }
    }


    And the compiler (if you've enabled --noImplicitReturns) notices that this function only sometimes returns a value, and so it complains.



    Of course, forEach() doesn't care about the return value of its callback, and that wasn't your intent anyway. The fix is to do what others have suggested... use find() instead of forEach(): ... this.objectCollector.find(o => o.getID()===id) ... Or use a for loop:



    for (let object of this.objectCollector) {
    if (object.getID() === id) {
    return object; // no callback, this returns from the getObject function.
    }
    }


    Hope that helps; good luck!






    share|improve this answer
























    • Thanks for the explanation @jcalz . Now it's clear!!

      – Alberto Valero
      Nov 21 '18 at 18:46














    1












    1








    1







    The error is inside the callback to forEach(), not on the getObject() call. Note that even though you are using an arrow function, it's still a function. And the return inside the callback is returning from the arrow function, not from getObject(). Note that for arrow functions, x => {return y} is equivalent to x => y. There's no way to return from an outer function from inside an arrow function.



    So this is your function:



    object => {
    if(object.getID() === id){
    return object;
    }
    }


    And the compiler (if you've enabled --noImplicitReturns) notices that this function only sometimes returns a value, and so it complains.



    Of course, forEach() doesn't care about the return value of its callback, and that wasn't your intent anyway. The fix is to do what others have suggested... use find() instead of forEach(): ... this.objectCollector.find(o => o.getID()===id) ... Or use a for loop:



    for (let object of this.objectCollector) {
    if (object.getID() === id) {
    return object; // no callback, this returns from the getObject function.
    }
    }


    Hope that helps; good luck!






    share|improve this answer













    The error is inside the callback to forEach(), not on the getObject() call. Note that even though you are using an arrow function, it's still a function. And the return inside the callback is returning from the arrow function, not from getObject(). Note that for arrow functions, x => {return y} is equivalent to x => y. There's no way to return from an outer function from inside an arrow function.



    So this is your function:



    object => {
    if(object.getID() === id){
    return object;
    }
    }


    And the compiler (if you've enabled --noImplicitReturns) notices that this function only sometimes returns a value, and so it complains.



    Of course, forEach() doesn't care about the return value of its callback, and that wasn't your intent anyway. The fix is to do what others have suggested... use find() instead of forEach(): ... this.objectCollector.find(o => o.getID()===id) ... Or use a for loop:



    for (let object of this.objectCollector) {
    if (object.getID() === id) {
    return object; // no callback, this returns from the getObject function.
    }
    }


    Hope that helps; good luck!







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 21 '18 at 18:31









    jcalzjcalz

    30.3k22850




    30.3k22850













    • Thanks for the explanation @jcalz . Now it's clear!!

      – Alberto Valero
      Nov 21 '18 at 18:46



















    • Thanks for the explanation @jcalz . Now it's clear!!

      – Alberto Valero
      Nov 21 '18 at 18:46

















    Thanks for the explanation @jcalz . Now it's clear!!

    – Alberto Valero
    Nov 21 '18 at 18:46





    Thanks for the explanation @jcalz . Now it's clear!!

    – Alberto Valero
    Nov 21 '18 at 18:46













    1














    I would use find() and add if check to throw the error.



    public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
    const id = obj.id;
    const item = this.objectCollector.find(object => object.getID() === id);
    if (!item) {
    throw new Error(`Scene.getObject(). Object ${id} not found`);
    }
    return item;
    }





    share|improve this answer




























      1














      I would use find() and add if check to throw the error.



      public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
      const id = obj.id;
      const item = this.objectCollector.find(object => object.getID() === id);
      if (!item) {
      throw new Error(`Scene.getObject(). Object ${id} not found`);
      }
      return item;
      }





      share|improve this answer


























        1












        1








        1







        I would use find() and add if check to throw the error.



        public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
        const id = obj.id;
        const item = this.objectCollector.find(object => object.getID() === id);
        if (!item) {
        throw new Error(`Scene.getObject(). Object ${id} not found`);
        }
        return item;
        }





        share|improve this answer













        I would use find() and add if check to throw the error.



        public getObject(obj:IObjectsCommonJSON): ObjectsCommon {
        const id = obj.id;
        const item = this.objectCollector.find(object => object.getID() === id);
        if (!item) {
        throw new Error(`Scene.getObject(). Object ${id} not found`);
        }
        return item;
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 18:21









        epascarelloepascarello

        154k14138187




        154k14138187






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417766%2ftypescript-gives-error-if-instead-of-returning-value-throws-error%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to pass form data using jquery Ajax to insert data in database?

            National Museum of Racing and Hall of Fame

            Guess what letter conforming each word