How to handle potential empty array when accessing by index in TypescriptHow do I remove an array item in TypeScript?Typescript Array restructureGet an error when I call object's properties in ArrayBind array value in HTMLCannot read property undefined, typescript assigning class array issueHow to handle 'this' in typescript/js ? need to convert Python code to TypescriptHow can i push to an custom typed arrayHow to declare an object of arrays in TypeScriptHow to make TypeScript compilation fail when accessing object property from an empty arrayHow to to push fetched data from backend service into a declared property within a class in typescript?

Do Iron Man suits sport waste management systems?

Can someone clarify Hamming's notion of important problems in relation to modern academia?

What do you call someone who asks many questions?

Is this answer explanation correct?

One verb to replace 'be a member of' a club

Why was the shrink from 8″ made only to 5.25″ and not smaller (4″ or less)

How can I deal with my CEO asking me to hire someone with a higher salary than me, a co-founder?

How obscure is the use of 令 in 令和?

Did 'Cinema Songs' exist during Hiranyakshipu's time?

My ex-girlfriend uses my Apple ID to log in to her iPad. Do I have to give her my Apple ID password to reset it?

How to install cross-compiler on Ubuntu 18.04?

How badly should I try to prevent a user from XSSing themselves?

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

How to prevent "they're falling in love" trope

Different meanings of こわい

How exploitable/balanced is this homebrew spell: Spell Permanency?

Avoiding the "not like other girls" trope?

What exactly is ineptocracy?

Is it "common practice in Fourier transform spectroscopy to multiply the measured interferogram by an apodizing function"? If so, why?

Why were 5.25" floppy drives cheaper than 8"?

Why is the sentence "Das ist eine Nase" correct?

Can compressed videos be decoded back to their uncompresed original format?

Why do I get negative height?

Does the Cone of Cold spell freeze water?



How to handle potential empty array when accessing by index in Typescript


How do I remove an array item in TypeScript?Typescript Array restructureGet an error when I call object's properties in ArrayBind array value in HTMLCannot read property undefined, typescript assigning class array issueHow to handle 'this' in typescript/js ? need to convert Python code to TypescriptHow can i push to an custom typed arrayHow to declare an object of arrays in TypeScriptHow to make TypeScript compilation fail when accessing object property from an empty arrayHow to to push fetched data from backend service into a declared property within a class in typescript?













0















What's the preferred way to access elements by index in an array in Typescript when the array also can be empty, leading to elements being undefined?



I'm coding a simple game in React with Typescript where I have a game variable consisting of an array of sets of type ISet. In this simplified example, ISet has a score property in it's interface, which I try to access



const game: ISet[] = [];
const currentSet = game[game.length - 1]; // 'currentSet' will be of type 'ISet', although it will be 'undefined' here
console.log(currentSet.score); // No Typescript error, although a 'Uncaught TypeError: Cannot read property 'score' of undefined' error will be thrown when run


How can I have Typescript detect currentSet potentially being undefined here?



I've tried to manually set currentSet's type to



const currentSet: ISet | undefined = game[game.length - 1];


but that doesn't work, and changing the type declaration to



const game: Array<ISet | undefined> = [];


allows undefined to be added to the array, which is not what I'm after and will lead to problems later on.



I've read through a couple of GitHub issues,
like this one, but couldn't find any suggestions on workarounds. Using something like last from Underscore would work, but it seems a bit overkill to a new package to bypass this issue.



Looking forward to some help!



Andreas










share|improve this question

















  • 1





    Weird.. unless you have a horribly old version of tslint it should work. Try running tslint -v maybe there is a global tslint version installed and that is getting picked up ..

    – Titian Cernicova-Dragomir
    Mar 7 at 9:33











  • Which tslint rule do you refer to that would catch this? no-spare-arrays will not work here. I'm running version 5.13, so that shouldn't be the problem.

    – Andreas Nasman
    Mar 7 at 11:23















0















What's the preferred way to access elements by index in an array in Typescript when the array also can be empty, leading to elements being undefined?



I'm coding a simple game in React with Typescript where I have a game variable consisting of an array of sets of type ISet. In this simplified example, ISet has a score property in it's interface, which I try to access



const game: ISet[] = [];
const currentSet = game[game.length - 1]; // 'currentSet' will be of type 'ISet', although it will be 'undefined' here
console.log(currentSet.score); // No Typescript error, although a 'Uncaught TypeError: Cannot read property 'score' of undefined' error will be thrown when run


How can I have Typescript detect currentSet potentially being undefined here?



I've tried to manually set currentSet's type to



const currentSet: ISet | undefined = game[game.length - 1];


but that doesn't work, and changing the type declaration to



const game: Array<ISet | undefined> = [];


allows undefined to be added to the array, which is not what I'm after and will lead to problems later on.



I've read through a couple of GitHub issues,
like this one, but couldn't find any suggestions on workarounds. Using something like last from Underscore would work, but it seems a bit overkill to a new package to bypass this issue.



Looking forward to some help!



Andreas










share|improve this question

















  • 1





    Weird.. unless you have a horribly old version of tslint it should work. Try running tslint -v maybe there is a global tslint version installed and that is getting picked up ..

    – Titian Cernicova-Dragomir
    Mar 7 at 9:33











  • Which tslint rule do you refer to that would catch this? no-spare-arrays will not work here. I'm running version 5.13, so that shouldn't be the problem.

    – Andreas Nasman
    Mar 7 at 11:23













0












0








0


1






What's the preferred way to access elements by index in an array in Typescript when the array also can be empty, leading to elements being undefined?



I'm coding a simple game in React with Typescript where I have a game variable consisting of an array of sets of type ISet. In this simplified example, ISet has a score property in it's interface, which I try to access



const game: ISet[] = [];
const currentSet = game[game.length - 1]; // 'currentSet' will be of type 'ISet', although it will be 'undefined' here
console.log(currentSet.score); // No Typescript error, although a 'Uncaught TypeError: Cannot read property 'score' of undefined' error will be thrown when run


How can I have Typescript detect currentSet potentially being undefined here?



I've tried to manually set currentSet's type to



const currentSet: ISet | undefined = game[game.length - 1];


but that doesn't work, and changing the type declaration to



const game: Array<ISet | undefined> = [];


allows undefined to be added to the array, which is not what I'm after and will lead to problems later on.



I've read through a couple of GitHub issues,
like this one, but couldn't find any suggestions on workarounds. Using something like last from Underscore would work, but it seems a bit overkill to a new package to bypass this issue.



Looking forward to some help!



Andreas










share|improve this question














What's the preferred way to access elements by index in an array in Typescript when the array also can be empty, leading to elements being undefined?



I'm coding a simple game in React with Typescript where I have a game variable consisting of an array of sets of type ISet. In this simplified example, ISet has a score property in it's interface, which I try to access



const game: ISet[] = [];
const currentSet = game[game.length - 1]; // 'currentSet' will be of type 'ISet', although it will be 'undefined' here
console.log(currentSet.score); // No Typescript error, although a 'Uncaught TypeError: Cannot read property 'score' of undefined' error will be thrown when run


How can I have Typescript detect currentSet potentially being undefined here?



I've tried to manually set currentSet's type to



const currentSet: ISet | undefined = game[game.length - 1];


but that doesn't work, and changing the type declaration to



const game: Array<ISet | undefined> = [];


allows undefined to be added to the array, which is not what I'm after and will lead to problems later on.



I've read through a couple of GitHub issues,
like this one, but couldn't find any suggestions on workarounds. Using something like last from Underscore would work, but it seems a bit overkill to a new package to bypass this issue.



Looking forward to some help!



Andreas







typescript types






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 9:21









Andreas NasmanAndreas Nasman

114




114







  • 1





    Weird.. unless you have a horribly old version of tslint it should work. Try running tslint -v maybe there is a global tslint version installed and that is getting picked up ..

    – Titian Cernicova-Dragomir
    Mar 7 at 9:33











  • Which tslint rule do you refer to that would catch this? no-spare-arrays will not work here. I'm running version 5.13, so that shouldn't be the problem.

    – Andreas Nasman
    Mar 7 at 11:23












  • 1





    Weird.. unless you have a horribly old version of tslint it should work. Try running tslint -v maybe there is a global tslint version installed and that is getting picked up ..

    – Titian Cernicova-Dragomir
    Mar 7 at 9:33











  • Which tslint rule do you refer to that would catch this? no-spare-arrays will not work here. I'm running version 5.13, so that shouldn't be the problem.

    – Andreas Nasman
    Mar 7 at 11:23







1




1





Weird.. unless you have a horribly old version of tslint it should work. Try running tslint -v maybe there is a global tslint version installed and that is getting picked up ..

– Titian Cernicova-Dragomir
Mar 7 at 9:33





Weird.. unless you have a horribly old version of tslint it should work. Try running tslint -v maybe there is a global tslint version installed and that is getting picked up ..

– Titian Cernicova-Dragomir
Mar 7 at 9:33













Which tslint rule do you refer to that would catch this? no-spare-arrays will not work here. I'm running version 5.13, so that shouldn't be the problem.

– Andreas Nasman
Mar 7 at 11:23





Which tslint rule do you refer to that would catch this? no-spare-arrays will not work here. I'm running version 5.13, so that shouldn't be the problem.

– Andreas Nasman
Mar 7 at 11:23












3 Answers
3






active

oldest

votes


















0














The best solution I could come up with was to use last from lodash and adding it as a separate package. I also added type definitions separately by installing @types/lodash.last.



My example case above would end up looking like this:



import last from 'lodash.last'

const game: ISet[] = [];
const currentSet = last(game); // 'currentSet' now has a type of 'ISet | undefined' 🤞
console.log(currentSet.score); // Object is possibly 'undefined'. ts(2532) 🎉





share|improve this answer






























    0














    This seems normal to me, you have an array of ISet, but it's just empty right now. arrays are allowed to be empty, this is how arrays work.



    just check to see if the array has any items in it first



    const game: ISet[] = [];
    if (game.length)
    const currentSet = game[game.length - 1];
    console.log(currentSet.score);
    else
    console.log("no games!");



    Doing something like game: (ISet | undefined)[] might imply that even when populated any item in the array might be undefined like this:



    [score: 4, score: 1, undefined, score: 5, undefined, undefined, score: 10]


    which is probably not your intention (I assume). Doing this might confuses you or other developers in the future.






    share|improve this answer

























    • The issue here is that there is no compile time error.

      – H.B.
      Mar 7 at 21:28











    • Again, I think this is pretty normal. I assume this exaple is pseudo-code and you probably aren't actually initializing an empty array and then attempting to access index -1 on it (0 length and then subtract 1) - Your array in real code probably gets values from something... so it's usually a good idea to ensure that an array has values on it before you try to access it.

      – Chris Barr
      Mar 7 at 21:35











    • Also, keep in mind that the compiler doesn't really keep track of how many items are in the array, that's something that happens at runtime. If I ran someArr[9999] I don't expect the TS compiler to know that my array only has 421 items in it, that's for me to check.

      – Chris Barr
      Mar 7 at 21:37











    • That this is normal is not the point. You want to catch as many issues as early as possible, and having the compiler return the obviously correct type would be great.

      – H.B.
      Mar 7 at 21:37











    • it is, you've set it to be an array of ISet objects, so that's what it's returning. If you access an item in the array that doesn't exist, that's not a compiler issue.

      – Chris Barr
      Mar 7 at 21:53


















    0














    Well, you could implement your own last and be more accurate in its typing:



    function last<T>(array: T[]): T | undefined // Explicit type

    return array[array.length - 1];






    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%2f55040145%2fhow-to-handle-potential-empty-array-when-accessing-by-index-in-typescript%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      The best solution I could come up with was to use last from lodash and adding it as a separate package. I also added type definitions separately by installing @types/lodash.last.



      My example case above would end up looking like this:



      import last from 'lodash.last'

      const game: ISet[] = [];
      const currentSet = last(game); // 'currentSet' now has a type of 'ISet | undefined' 🤞
      console.log(currentSet.score); // Object is possibly 'undefined'. ts(2532) 🎉





      share|improve this answer



























        0














        The best solution I could come up with was to use last from lodash and adding it as a separate package. I also added type definitions separately by installing @types/lodash.last.



        My example case above would end up looking like this:



        import last from 'lodash.last'

        const game: ISet[] = [];
        const currentSet = last(game); // 'currentSet' now has a type of 'ISet | undefined' 🤞
        console.log(currentSet.score); // Object is possibly 'undefined'. ts(2532) 🎉





        share|improve this answer

























          0












          0








          0







          The best solution I could come up with was to use last from lodash and adding it as a separate package. I also added type definitions separately by installing @types/lodash.last.



          My example case above would end up looking like this:



          import last from 'lodash.last'

          const game: ISet[] = [];
          const currentSet = last(game); // 'currentSet' now has a type of 'ISet | undefined' 🤞
          console.log(currentSet.score); // Object is possibly 'undefined'. ts(2532) 🎉





          share|improve this answer













          The best solution I could come up with was to use last from lodash and adding it as a separate package. I also added type definitions separately by installing @types/lodash.last.



          My example case above would end up looking like this:



          import last from 'lodash.last'

          const game: ISet[] = [];
          const currentSet = last(game); // 'currentSet' now has a type of 'ISet | undefined' 🤞
          console.log(currentSet.score); // Object is possibly 'undefined'. ts(2532) 🎉






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 14:23









          Andreas NasmanAndreas Nasman

          114




          114























              0














              This seems normal to me, you have an array of ISet, but it's just empty right now. arrays are allowed to be empty, this is how arrays work.



              just check to see if the array has any items in it first



              const game: ISet[] = [];
              if (game.length)
              const currentSet = game[game.length - 1];
              console.log(currentSet.score);
              else
              console.log("no games!");



              Doing something like game: (ISet | undefined)[] might imply that even when populated any item in the array might be undefined like this:



              [score: 4, score: 1, undefined, score: 5, undefined, undefined, score: 10]


              which is probably not your intention (I assume). Doing this might confuses you or other developers in the future.






              share|improve this answer

























              • The issue here is that there is no compile time error.

                – H.B.
                Mar 7 at 21:28











              • Again, I think this is pretty normal. I assume this exaple is pseudo-code and you probably aren't actually initializing an empty array and then attempting to access index -1 on it (0 length and then subtract 1) - Your array in real code probably gets values from something... so it's usually a good idea to ensure that an array has values on it before you try to access it.

                – Chris Barr
                Mar 7 at 21:35











              • Also, keep in mind that the compiler doesn't really keep track of how many items are in the array, that's something that happens at runtime. If I ran someArr[9999] I don't expect the TS compiler to know that my array only has 421 items in it, that's for me to check.

                – Chris Barr
                Mar 7 at 21:37











              • That this is normal is not the point. You want to catch as many issues as early as possible, and having the compiler return the obviously correct type would be great.

                – H.B.
                Mar 7 at 21:37











              • it is, you've set it to be an array of ISet objects, so that's what it's returning. If you access an item in the array that doesn't exist, that's not a compiler issue.

                – Chris Barr
                Mar 7 at 21:53















              0














              This seems normal to me, you have an array of ISet, but it's just empty right now. arrays are allowed to be empty, this is how arrays work.



              just check to see if the array has any items in it first



              const game: ISet[] = [];
              if (game.length)
              const currentSet = game[game.length - 1];
              console.log(currentSet.score);
              else
              console.log("no games!");



              Doing something like game: (ISet | undefined)[] might imply that even when populated any item in the array might be undefined like this:



              [score: 4, score: 1, undefined, score: 5, undefined, undefined, score: 10]


              which is probably not your intention (I assume). Doing this might confuses you or other developers in the future.






              share|improve this answer

























              • The issue here is that there is no compile time error.

                – H.B.
                Mar 7 at 21:28











              • Again, I think this is pretty normal. I assume this exaple is pseudo-code and you probably aren't actually initializing an empty array and then attempting to access index -1 on it (0 length and then subtract 1) - Your array in real code probably gets values from something... so it's usually a good idea to ensure that an array has values on it before you try to access it.

                – Chris Barr
                Mar 7 at 21:35











              • Also, keep in mind that the compiler doesn't really keep track of how many items are in the array, that's something that happens at runtime. If I ran someArr[9999] I don't expect the TS compiler to know that my array only has 421 items in it, that's for me to check.

                – Chris Barr
                Mar 7 at 21:37











              • That this is normal is not the point. You want to catch as many issues as early as possible, and having the compiler return the obviously correct type would be great.

                – H.B.
                Mar 7 at 21:37











              • it is, you've set it to be an array of ISet objects, so that's what it's returning. If you access an item in the array that doesn't exist, that's not a compiler issue.

                – Chris Barr
                Mar 7 at 21:53













              0












              0








              0







              This seems normal to me, you have an array of ISet, but it's just empty right now. arrays are allowed to be empty, this is how arrays work.



              just check to see if the array has any items in it first



              const game: ISet[] = [];
              if (game.length)
              const currentSet = game[game.length - 1];
              console.log(currentSet.score);
              else
              console.log("no games!");



              Doing something like game: (ISet | undefined)[] might imply that even when populated any item in the array might be undefined like this:



              [score: 4, score: 1, undefined, score: 5, undefined, undefined, score: 10]


              which is probably not your intention (I assume). Doing this might confuses you or other developers in the future.






              share|improve this answer















              This seems normal to me, you have an array of ISet, but it's just empty right now. arrays are allowed to be empty, this is how arrays work.



              just check to see if the array has any items in it first



              const game: ISet[] = [];
              if (game.length)
              const currentSet = game[game.length - 1];
              console.log(currentSet.score);
              else
              console.log("no games!");



              Doing something like game: (ISet | undefined)[] might imply that even when populated any item in the array might be undefined like this:



              [score: 4, score: 1, undefined, score: 5, undefined, undefined, score: 10]


              which is probably not your intention (I assume). Doing this might confuses you or other developers in the future.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 7 at 21:29

























              answered Mar 7 at 21:26









              Chris BarrChris Barr

              11.9k1465103




              11.9k1465103












              • The issue here is that there is no compile time error.

                – H.B.
                Mar 7 at 21:28











              • Again, I think this is pretty normal. I assume this exaple is pseudo-code and you probably aren't actually initializing an empty array and then attempting to access index -1 on it (0 length and then subtract 1) - Your array in real code probably gets values from something... so it's usually a good idea to ensure that an array has values on it before you try to access it.

                – Chris Barr
                Mar 7 at 21:35











              • Also, keep in mind that the compiler doesn't really keep track of how many items are in the array, that's something that happens at runtime. If I ran someArr[9999] I don't expect the TS compiler to know that my array only has 421 items in it, that's for me to check.

                – Chris Barr
                Mar 7 at 21:37











              • That this is normal is not the point. You want to catch as many issues as early as possible, and having the compiler return the obviously correct type would be great.

                – H.B.
                Mar 7 at 21:37











              • it is, you've set it to be an array of ISet objects, so that's what it's returning. If you access an item in the array that doesn't exist, that's not a compiler issue.

                – Chris Barr
                Mar 7 at 21:53

















              • The issue here is that there is no compile time error.

                – H.B.
                Mar 7 at 21:28











              • Again, I think this is pretty normal. I assume this exaple is pseudo-code and you probably aren't actually initializing an empty array and then attempting to access index -1 on it (0 length and then subtract 1) - Your array in real code probably gets values from something... so it's usually a good idea to ensure that an array has values on it before you try to access it.

                – Chris Barr
                Mar 7 at 21:35











              • Also, keep in mind that the compiler doesn't really keep track of how many items are in the array, that's something that happens at runtime. If I ran someArr[9999] I don't expect the TS compiler to know that my array only has 421 items in it, that's for me to check.

                – Chris Barr
                Mar 7 at 21:37











              • That this is normal is not the point. You want to catch as many issues as early as possible, and having the compiler return the obviously correct type would be great.

                – H.B.
                Mar 7 at 21:37











              • it is, you've set it to be an array of ISet objects, so that's what it's returning. If you access an item in the array that doesn't exist, that's not a compiler issue.

                – Chris Barr
                Mar 7 at 21:53
















              The issue here is that there is no compile time error.

              – H.B.
              Mar 7 at 21:28





              The issue here is that there is no compile time error.

              – H.B.
              Mar 7 at 21:28













              Again, I think this is pretty normal. I assume this exaple is pseudo-code and you probably aren't actually initializing an empty array and then attempting to access index -1 on it (0 length and then subtract 1) - Your array in real code probably gets values from something... so it's usually a good idea to ensure that an array has values on it before you try to access it.

              – Chris Barr
              Mar 7 at 21:35





              Again, I think this is pretty normal. I assume this exaple is pseudo-code and you probably aren't actually initializing an empty array and then attempting to access index -1 on it (0 length and then subtract 1) - Your array in real code probably gets values from something... so it's usually a good idea to ensure that an array has values on it before you try to access it.

              – Chris Barr
              Mar 7 at 21:35













              Also, keep in mind that the compiler doesn't really keep track of how many items are in the array, that's something that happens at runtime. If I ran someArr[9999] I don't expect the TS compiler to know that my array only has 421 items in it, that's for me to check.

              – Chris Barr
              Mar 7 at 21:37





              Also, keep in mind that the compiler doesn't really keep track of how many items are in the array, that's something that happens at runtime. If I ran someArr[9999] I don't expect the TS compiler to know that my array only has 421 items in it, that's for me to check.

              – Chris Barr
              Mar 7 at 21:37













              That this is normal is not the point. You want to catch as many issues as early as possible, and having the compiler return the obviously correct type would be great.

              – H.B.
              Mar 7 at 21:37





              That this is normal is not the point. You want to catch as many issues as early as possible, and having the compiler return the obviously correct type would be great.

              – H.B.
              Mar 7 at 21:37













              it is, you've set it to be an array of ISet objects, so that's what it's returning. If you access an item in the array that doesn't exist, that's not a compiler issue.

              – Chris Barr
              Mar 7 at 21:53





              it is, you've set it to be an array of ISet objects, so that's what it's returning. If you access an item in the array that doesn't exist, that's not a compiler issue.

              – Chris Barr
              Mar 7 at 21:53











              0














              Well, you could implement your own last and be more accurate in its typing:



              function last<T>(array: T[]): T | undefined // Explicit type

              return array[array.length - 1];






              share|improve this answer



























                0














                Well, you could implement your own last and be more accurate in its typing:



                function last<T>(array: T[]): T | undefined // Explicit type

                return array[array.length - 1];






                share|improve this answer

























                  0












                  0








                  0







                  Well, you could implement your own last and be more accurate in its typing:



                  function last<T>(array: T[]): T | undefined // Explicit type

                  return array[array.length - 1];






                  share|improve this answer













                  Well, you could implement your own last and be more accurate in its typing:



                  function last<T>(array: T[]): T | undefined // Explicit type

                  return array[array.length - 1];







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 7 at 21:35









                  H.B.H.B.

                  122k22244325




                  122k22244325



























                      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%2f55040145%2fhow-to-handle-potential-empty-array-when-accessing-by-index-in-typescript%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

                      Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                      Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                      Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved