{"id":4416,"date":"2022-10-03T19:47:37","date_gmt":"2022-10-04T00:47:37","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=4416"},"modified":"2022-10-03T19:50:40","modified_gmt":"2022-10-04T00:50:40","slug":"typescript-array-find-possibly-undefined","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-array-find-possibly-undefined\/","title":{"rendered":"(Solved) TypeScript Array.find() possibly &#8216;undefined&#8217;"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Errors like &#8220;TS2532<\/strong>: <strong>Object is possible  &#8216;undefined'&#8221; can happen after defining the value of a variable by using the <code>array.find()<\/code> method<\/strong>. <strong>Here are the possible reasons why  the<code>array.find()<\/code> method returns <code>undefined<\/code><\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>The predicate parameter or callback function passed to the <code>array.find()<\/code> doesn&#8217;t explicitly use the <code>return<\/code> keyword to return a truthy value.<\/strong><\/li><li><strong>The predicate parameter or callback function never returns a truthy value.<\/strong><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example of the error described aboved.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>interface Car {\n  year: number;\n  brand: string;\n  model: string;\n  color: string;\n}\n\ntype Cars = Car&#91;];\n\nconst CARS: Cars = &#91;\n  {\n    year: 2022,\n    brand: 'Ford',\n    model: 'Bronco',\n    color: \"White\"\n  }, {\n    year: 2012,\n    brand: \"Dodge\",\n    model: \"Challenger\",\n    color: \"Black\"\n  }, \n  {\n    year: 2018,\n    brand: \"Toyota\",\n    model: \"Prius\",\n    color: \"Silver\"\n  }\n];\n\nconst toyota = CARS.find(car => {\n  if (car.brand === \"Toyota\") {\n    console.log('Here it is!')\n  }\n\n  \/\/ ? This callback function never returns a truthy response\n});\n\n\/\/ \u274c Object is possibly 'undefined'.\nconsole.log('I have a Toyota ', toyota.model);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the previous example, even though there is a condition that checks if a <code>car<\/code> is Toyota,  the callback function never returns a truthy response after executing the logic on each element of the array.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>To fix the error &#8220;Object is possibly &#8216;undefined'&#8221;, ensure the callback function returns a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Truthy\" target=\"_blank\" rel=\"noopener\">truthy<\/a> response and the predicate defined in the callback function is met at least once with one of the elements of the array<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>const toyota = CARS.find(car => {\n  \/\/ \u2705 Callback function uses the 'return' keyword to return response\n  \/\/ \u2705 Predicate will be met as CARS array has at least one \"Toyota\" car\n  return car.brand === \"Toyota\";\n});\n\nconsole.log('I have a Toyota ', toyota.model);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If after making the above changes, you still see the error &#8220;Object is possibly &#8216;undefined'&#8221;,<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"466\" height=\"95\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/10\/image.png\" alt=\"\" class=\"wp-image-4420\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/10\/image.png 466w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/10\/image-300x61.png 300w\" sizes=\"auto, (max-width: 466px) 100vw, 466px\" \/><figcaption>Still returning &#8220;Object is possibly &#8216;undefined'&#8221;<\/figcaption><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">this is because TypeScript by default defines the returned type of the result as either the type <code>T<\/code> from an array of type <code>T[]<\/code> or <code>undefined<\/code> . It is a safety mechanism as TypeScript cannot predict, even if you have hardcoded array, whether the result from using <code>array.find()<\/code> will always return a type <code>T<\/code> .<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are four possible solutions and prevent from getting &#8220;Object is possibly &#8216;undefined&#8217; errors at compile time.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Use an if condition to check the value returned from using the <code>array.find()<\/code> method is not <code>undefined<\/code>.<\/li><li>Use the optional chaining operator (preferred)<\/li><li>Explicitly define the type of the result returned from using the <code>array.find()<\/code> method.<\/li><li>Disable type checking for a line (not recommended)<\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Here are examples of each solution.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>\/\/ \u2705 Explicitly checking the result returned from using the array.find() method\n\/\/ makes clear a value different than undefined was returned\nif (toyota !== undefined) {\n  console.log('I have a Toyota ', toyota.model);\n}<\/code><\/pre>\n\n\n\n<p class=\"has-light-green-cyan-background-color has-background wp-block-paragraph\">\u2705 Using conditional checks to verify the result returned from using the <code>array.find()<\/code> method is the solution that makes your code more predictable and error free.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>\/\/ \u2705 Using optional chaining operator\nconsole.log('I have a Toyota ', toyota?.model);<\/code><\/pre>\n\n\n\n<p class=\"has-pale-cyan-blue-background-color has-background wp-block-paragraph\">Using the optional chaining operator is a common solution used among TypeScript developers. Be aware though that using the optional chaining operator opens the possibility to working with undefined values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Another option is to explicitly define the result type returned by the <code>array.find()<\/code> method. In this case, the expected result is an object of type <code>Car<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>\/\/ \u2705 Defining the type \"&lt;Car>\" of the result returned by the array.find() method\nconst toyota = &lt;Car>CARS.find(car => {\r\n  return car.brand === \"Toyota\";\r\n});\r\n\r\r\nconsole.log('I have a Toyota ', toyota.model);\r<\/code><\/pre>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background wp-block-paragraph\"><strong>Note:<\/strong> Explicitly define the result type when you are completely sure the callback passed to the <code>array.find()<\/code> method will always return a truthy value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, you could also disable type checking the line where the error &#8220;Object is possibly &#8216;undefined'&#8221; is generated by using the <code>\/\/ @ts-ignore<\/code> comment.<\/p>\n\n\n\n<pre class=\"wp-block-code language-typescript\"><code>\/\/ ? Disabling type checking is always an option to get rid of TypeScript\n\/\/ errors, but I personally don't recommend using it if there are other alternatives.\n\/\/ @ts-ignore:next-line \r\nconsole.log('I have a Toyota ', toyota.model);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Out of the solutions presented, this is the least recommended solution as sometimes you are not only preventing TypeScript from detecting the &#8220;Object is possibly &#8216;undefined'&#8221; error, but other syntax errors. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Errors like &#8220;TS2532: Object is possible &#8216;undefined&#8217;&#8221; can happen after defining the value of a variable by using the array.find() method. Here are the possible reasons why thearray.find() method returns undefined: The predicate parameter or callback function passed to the array.find() doesn&#8217;t explicitly use the return keyword to return a truthy value. The predicate parameter &#8230; <a title=\"(Solved) TypeScript Array.find() possibly &#8216;undefined&#8217;\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/typescript-array-find-possibly-undefined\/\" aria-label=\"More on (Solved) TypeScript Array.find() possibly &#8216;undefined&#8217;\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":4426,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[19],"tags":[],"class_list":["post-4416","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-typescript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4416","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=4416"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4416\/revisions"}],"predecessor-version":[{"id":4432,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4416\/revisions\/4432"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/4426"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=4416"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=4416"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=4416"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}