{"id":20793,"date":"2023-08-22T11:12:53","date_gmt":"2023-08-22T09:12:53","guid":{"rendered":"https:\/\/www.oimmei.com\/react-javascript-parse-di-oggetti-tipati-con-yup-cast\/"},"modified":"2025-07-29T11:05:49","modified_gmt":"2025-07-29T09:05:49","slug":"react-javascript-typed-object-parsing-with-yup-cast","status":"publish","type":"post","link":"https:\/\/www.oimmei.com\/en\/react-javascript-typed-object-parsing-with-yup-cast\/","title":{"rendered":"Typed object parsing with Yup cast"},"content":{"rendered":"\r\n<p class=\"wp-block-paragraph\">While working on a project based on <a href=\"https:\/\/react.dev\/\" target=\"_blank\" rel=\"noreferrer noopener\">React<\/a>, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Window\/localStorage?retiredLocale=it\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>localStorage<\/strong><\/a>, a query string. For instance, you could have to retrieve data serialized in some text form, perhaps even data you previously saved somewhere yourself in order to store a preference for the user of your application.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Retrieving this kind of information, regardless of how you do it, is usually easy enough: you just query the data source, get the item or the list you\u2019re looking for and that\u2019s it.<br \/><br \/>.\u2026or is it?<br \/><br \/>JavaScript is a dynamically typed language and, even though you could and probably should use <a href=\"https:\/\/www.typescriptlang.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">TypeScript<\/a> &#8211; like we do &#8211; as a helping tool to identify type errors before it\u2019s too late, variables and properties will still have dynamic typing at runtime. For this reason, you may find yourself dealing with values you don\u2019t expect, especially when querying text-based data sources.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Typically, this happens with numeric fields, but every kind of non-text value is potentially affected: you have a numeric value stored somewhere, you fetch it from the data source, and you use it in a strict comparison or in some function expecting to be playing with a <strong>number<\/strong>, only to then find out it\u2019s actually a string, often leading to sneaky and obscure bugs. Let\u2019s see an example of that.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Here\u2019s a very common situation for anyone working in web development: we\u2019re creating a <strong>React web app that stores a delicious pizza in the query string<\/strong>, and later retrieves its data to display them to the user. Boy, if I had a nickel.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Let\u2019s start by instantiating a <a href=\"https:\/\/create-react-app.dev\/\">create-react-project<\/a> with TypeScript, just the way we like it, and let\u2019s get to work.<\/p>\r\n\r\n\r\n\r\n<div class=\"wp-block-group is-layout-constrained wp-block-group-is-layout-constrained\">\r\n<pre class=\"wp-block-syntaxhighlighter-code\">npx create-react-app react18-typed-parsing --template typescript<\/pre>\r\n<\/div>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">We\u2019ll add a few libraries, as well. Specifically <a href=\"https:\/\/www.npmjs.com\/package\/qs\"><strong>Qs<\/strong><\/a>, to serialize and deserialize objects in the query string, along with <a href=\"https:\/\/www.npmjs.com\/package\/react-router\"><strong>react-router<\/strong><\/a> and <a href=\"https:\/\/www.npmjs.com\/package\/react-router-dom\"><strong>react-router-dom<\/strong><\/a> o manipulate said query string, of course with the related type declarations.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">npm install qs react-router react-router-domnpm install -D @types\/qs<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">First off, let\u2019s create a data model for our pizza, with a numeric ID and a pair of text fields.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/models\/Pizza.ts\r\nexport interface Pizza {\r\n  id: number\r\n\r\n  name: string\r\n\r\n  description?: string\r\n}\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Our web app will consist mainly of two components.<\/p>\r\n\r\n\r\n\r\n<ul class=\"wp-block-list\">\r\n<li><strong>PizzaWriter<\/strong> will take a <strong>Pizza<\/strong> and set it in the query string.<\/li>\r\n\r\n\r\n\r\n<li><strong>PizzaReader<\/strong> will wait for a <strong>Pizza<\/strong> to appear in the query string. As soon as that happens, it will instantly consume the thing and show its data to the user, kind of like me when the Just Eat rider arrives.<\/li>\r\n<\/ul>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The components will be inside the container <strong>PizzaWrapper<\/strong>\u2026<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/pages\/PizzaWrapper.tsx\r\nimport React, {ReactElement} from 'react';\r\nimport PizzaWriter from '..\/components\/PizzaWriter';\r\nimport PizzaReader from '..\/components\/PizzaReader';\r\n\r\nconst PizzaWrapper = (): ReactElement | null =&gt; {\r\n  return (\r\n    &lt;&gt;\r\n      &lt;PizzaWriter\/&gt;\r\n      &lt;PizzaReader\/&gt;\r\n    &lt;\/&gt;\r\n  );\r\n}\r\n\r\nexport default PizzaWrapper;\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\u2026which will act as the root component.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/App.tsx\r\nimport React from 'react';\r\nimport {\r\n  createBrowserRouter,\r\n  RouterProvider,\r\n} from \"react-router-dom\";\r\nimport '.\/App.css';\r\nimport PizzaWrapper from '.\/pages\/PizzaWrapper';\r\n\r\nconst router = createBrowserRouter([\r\n{\r\n    path: '\/',\r\n    element: &lt;PizzaWrapper\/&gt;,\r\n  },\r\n]);\r\n\r\nfunction App() {\r\n  return (\r\n    &lt;RouterProvider router={router}\/&gt;\r\n  );\r\n}\r\n\r\nexport default App;\r\n\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\"><strong>PizzaWriter<\/strong> is pretty simple: when a button is clicked, it serializes a Pizza object using <strong>Qs<\/strong> and sets it in the query string using the hook <a href=\"https:\/\/reactrouter.com\/zh\/main\/hooks\/use-search-params\"><strong>useSearchParams<\/strong><\/a> from <strong>react-router-dom<\/strong>. <a href=\"https:\/\/reactrouter.com\/zh\/main\/hooks\/use-search-params\"><strong>useSearchParams<\/strong><\/a>.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/components\/PizzaWriter.tsx\r\nimport React, {ReactElement} from 'react';\r\nimport {useSearchParams} from 'react-router-dom';\r\nimport Qs from 'qs';\r\nimport {Pizza} from '..\/models\/Pizza';\r\n\r\n\/\/ The pizza to be delivered via query string.\r\nconst pizzaToWrite: Pizza = {\r\n  id: 1,\r\n  name: 'Pepperoni',\r\n  description: 'So good!',\r\n};\r\n\r\nconst PizzaWriter = (): ReactElement =&gt; {\r\n  \/\/ Function to manipulate the query string.\r\n  const [, setSearchParams] = useSearchParams();\r\n\r\n  \/\/ Saving the pizza in the query string on click.\r\n  const savePizzaInQueryString = (): void =&gt; {\r\n    setSearchParams(Qs.stringify(pizzaToWrite));\r\n  }\r\n\r\n  return (\r\n    &lt;div className={'querystring-writer'}&gt;\r\n      &lt;h1&gt;PizzaWriter&lt;\/h1&gt;\r\n      &lt;button onClick={savePizzaInQueryString}&gt;\r\n        Save pizza in query string\r\n      &lt;\/button&gt;\r\n    &lt;\/div&gt;\r\n);\r\n}\r\n\r\nexport default PizzaWriter;\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\"><strong>PizzaReader<\/strong> is where things start to get tricky. Basically, we want to listen to the query string, again using <strong>useSearchParams<\/strong>, so we\u2019re ready to get a <strong>Pizza<\/strong> and set it in the state. <strong>b<\/strong> The component is expecting a pepperoni pizza, so let\u2019s also check the ID to make sure the item is exactly the one that was ordered.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The question now is: how do we make sure the object we\u2019re getting is actually a <strong>Pizza<\/strong>?<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/components\/PizzaReader.tsx\r\nimport React, {ReactElement, useEffect, useState} from 'react';\r\nimport {useSearchParams} from 'react-router-dom';\r\nimport Qs from 'qs';\r\nimport {Pizza} from '..\/models\/Pizza';\r\n\r\n\/\/ The pizza we're expecting to find in the query string.\r\nconst pizzaToRead: Pizza = {\r\n  id: 1,\r\n  name: 'Pepperoni',\r\n  description: 'So good!',\r\n};\r\n\r\nconst PizzaReader = (): ReactElement | null =&gt; {\r\n  const [searchParams] = useSearchParams();\r\n\r\n  \/\/ The pizza retrieved from the query string, if any.\r\n  const [pizza, setPizza] =\r\n    useState&lt;Pizza | null&gt;(null);\r\n\r\n  useEffect(() =&gt; {\r\n    \/\/ Parsing the pizza in the query string.\r\n    const pizzaRaw = Qs.parse(searchParams.toString());\r\n\r\n    \/\/ TODO: what now?\r\n  }, [searchParams]);\r\n\r\n  \/\/ Displaying information about the pizza, if any.\r\n  return (\r\n    &lt;div className={'querystring-reader'}&gt;\r\n      &lt;h1&gt;PizzaReader&lt;\/h1&gt;\r\n      {pizza !== null ? (\r\n        &lt;div className={'pizza-info'}&gt;\r\n          &lt;div&gt;\r\n            &lt;div className={'bold'}&gt;ID&lt;\/div&gt;\r\n            &lt;div&gt;{pizza.id}&lt;\/div&gt;\r\n          &lt;\/div&gt;\r\n          &lt;div&gt;\r\n            &lt;div className={'bold'}&gt;Name&lt;\/div&gt;\r\n            &lt;div&gt;{pizza.name}&lt;\/div&gt;\r\n          &lt;\/div&gt;\r\n          &lt;div&gt;\r\n            &lt;div className={'bold'}&gt;Description&lt;\/div&gt;\r\n            &lt;div&gt;{pizza.description}&lt;\/div&gt;\r\n          &lt;\/div&gt;\r\n          &lt;div&gt;\r\n            {\/* If this is a pepperoni pizza, meaning the one we expect, saying Yes. *\/}\r\n            &lt;div className={'bold'}&gt;Pepperoni&lt;\/div&gt;\r\n            &lt;div&gt;{pizza.id === pizzaToRead.id ? 'Yes' : 'No'}&lt;\/div&gt;\r\n          &lt;\/div&gt;\r\n        &lt;\/div&gt;\r\n      ) : (\r\n        'No pizza in the query string :('\r\n      )}\r\n    &lt;\/div&gt;\r\n  );\r\n};\r\n\r\nexport default PizzaReader;\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">A possible approach is to define a custom <a href=\"https:\/\/www.typescriptlang.org\/docs\/handbook\/2\/narrowing.html#using-type-predicates\">type guard<\/a>, so we can check for the object to have the properties we expect.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/helpers\/pizzaHelper.ts\r\nimport {Pizza} from '..\/models\/Pizza';\r\n\r\n\/\/ Type guard to make sure any object is a Pizza.\r\nexport const isPizza = (obj: any): obj is Pizza =&gt; {\r\n  return 'id' in obj &amp;&amp; 'name' in obj &amp;&amp; 'description' in obj;\r\n}\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Let\u2019s try using this to complete the effect in <strong>PizzaReade<\/strong>r<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">import {isPizza} from '..\/helpers\/pizzaHelper';\r\n\r\n \u2026\r\n\r\n  useEffect(() =&gt; {\r\n    \/\/ Parsing the pizza in the query string.\r\n    const pizzaRaw = Qs.parse(searchParams.toString());\r\n\r\n    \/\/ If the object is a pizza, saving that in the state.\r\n    if (isPizza(pizzaRaw)) {\r\n      setPizza(pizzaRaw);\r\n    }\r\n  }, [searchParams]);\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">According to TypeScript, everything is fine. If we run our web app using\u2026<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">npm run start<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\u2026and open the browser, we\u2019ll see <strong>PizzaReader<\/strong> ready to receive its hard-earned <strong>Pizza<\/strong>.<img fetchpriority=\"high\" decoding=\"async\" class=\"alignnone\" src=\"https:\/\/lh6.googleusercontent.com\/0y2ewKwrkKh_g3RPcoHXK-Umk30qh7XapJ8GsmQ8LSKsMCs6fjZlb-U-KlcyKIoVGRSwHexWVXkRuNZaQymW-0DoIQ-r_RUX0nxDRac9UDeYJr1GlUYLFIzPju2fuSYQqfeskeqU9ZpaGOududJ53gM\" alt=\"pizza writer pizza reader\" width=\"602\" height=\"429\" \/><\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Let\u2019s press the button to deliver our marvelous baked disc of dough, and let\u2019s see what changes.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The\u00a0 result may appear satisfying at first glance, but something\u2019s not right. The data are correct, except for the fact that <strong>PizzaReader<\/strong> doesn\u2019t realize this is a pepperoni pizza. Why is that?<img decoding=\"async\" class=\"alignnone\" src=\"https:\/\/lh3.googleusercontent.com\/giaU2GC9fiE8JZyKH8kaliIRnRUFzNrKEKGjyyIRUJhK3hVIKkTkL_bS3TEdCFPH4YWSSqhyGgMIddL5arnLVhf8yIM-K5VA7dhng2mKQEMd946j54xSMt9Oar_-0dsCThUhTDcuX0LRGN6toBq2Yuk\" alt=\"pizza writer pizza reader\" width=\"602\" height=\"429\" \/><\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The answer is in the comparison we made on the ID.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">&lt;div&gt;\r\n            {\/* If this is a pepperoni pizza, meaning the one we expect, saying Yes. *\/}\r\n            &lt;div className={'bold'}&gt;Pepperoni&lt;\/div&gt;\r\n            &lt;div&gt;{pizza.id === pizzaToRead.id ? 'Yes' : 'No'}&lt;\/div&gt;\r\n          &lt;\/div&gt;\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Here\u2019s the issue: <strong>pizzaToRead<\/strong> was defined in our own code according to its interface, while <strong>pizza<\/strong> is retrieved from the query string. In the former, the ID is a <strong>number<\/strong>; in the latter, however, since a query string doesn\u2019t have any indication about typing, every property is a <strong>string<\/strong>. Thus, the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/Strict_equality\">strict equality operator<\/a> returns <strong>false<\/strong>; the types are different, even though TypeScript has no way to know beforehand.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Solving this situation is not as easy as it may look. Sure, for such a simple case we could resort to a plain <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/Equality\">equality operator<\/a>, but what about complex scenarios? What if we have to use a specific method from the <strong>String<\/strong> or the <strong>Number<\/strong> prototype?<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">One might try refactoring the type guard <strong>isPizza<\/strong> to be more strict, so it checks the types of the properties as well as their existence, but that would cause the web app to think the object in the query string is not a <strong>Pizza<\/strong> at all, leaving poor <strong>PizzaReader<\/strong> on an empty state &#8211; and stomach. So? Do we have to create some complex parser function for every interface in our project?<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">No: there is a quicker and safer way, and it comes from the <a href=\"https:\/\/www.npmjs.com\/package\/yup\"><strong>Yup<\/strong><\/a> library.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">If you\u2019re already used to React, you\u2019ve likely heard about <strong>Yup<\/strong>. It\u2019s one of the most popular libraries around when it comes to form validation, often used alongside <a href=\"https:\/\/www.npmjs.com\/package\/formik\"><strong>Formik<\/strong><\/a>. Form validation is not the only thing <strong>Yup<\/strong> is good at, though: right now, we\u2019re looking for the <a href=\"https:\/\/github.com\/jquense\/yup#schemacastvalue-any-options---infertypeschema\"><strong>cast<\/strong><\/a> method. It\u2019s <strong>a feature that, given a value<\/strong> which may or may not be an object, <strong>attempts to build a second value which respects a specific schema<\/strong>, just like the schema you\u2019d use while validating a form.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Let\u2019s install <strong>Yup<\/strong> and its type declarations\u2026<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">npm install yup\r\nnpm install -D @types\/yup\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\u2026and add a <strong>Yup<\/strong> schema next to the <strong>Pizza<\/strong> interface.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/models\/Pizza.ts\r\nimport * as yup from 'yup';\r\n\r\nexport interface Pizza {\r\n  id: number\r\n\r\n  name: string\r\n\r\n  description?: string\r\n}\r\n\r\n\/\/ Yup schema for a Pizza object.\r\nexport const pizzaSchema = yup.object({\r\n  id: yup.number().required(),\r\n  name: yup.string().required(),\r\n  description: yup.string(),\r\n});\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Finally, we\u2019ll add a third component, <strong>PizzaTypedReader<\/strong>. Its structure will be the same as PizzaReader, only the value from the query string will be parsed using the schema.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">import React, {ReactElement, useEffect, useState} from 'react';\r\n\/\/ src\/components\/PizzaTypedReader.tsx\r\nimport {useSearchParams} from 'react-router-dom';\r\nimport Qs from 'qs';\r\nimport {Pizza, pizzaSchema} from '..\/models\/Pizza';\r\n\r\n\/\/ The pizza we're expecting to find in the query string.\r\nconst pizzaToRead: Pizza = {\r\n  id: 1,\r\n  name: 'Pepperoni',\r\n  description: 'So good!',\r\n};\r\n\r\nconst PizzaTypedReader = (): ReactElement | null =&gt; {\r\n\r\n  \u2026\r\n\r\n  useEffect(() =&gt; {\r\n    \/\/ Parsing the pizza in the query string.\r\n    const pizzaRaw = Qs.parse(searchParams.toString());\r\n\r\n    \/\/ Trying to parse a pizza with Yup.cast.\r\n    try {\r\n      const newPizza = pizzaSchema.cast(pizzaRaw) as Pizza;\r\n\r\n      \/\/ The object is a pizza.\r\n      setPizza(newPizza);\r\n    } catch (error) {\r\n      \/\/ The object is *not* a pizza.\r\n      setPizza(null);\r\n    }\r\n  }, [searchParams]);\r\n\r\n  \u2026\r\n};\r\n\r\nexport default PizzaTypedReader;\r\n\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">The <strong>cast<\/strong> method takes the object from the query string and returns a new object respecting the given schema, but only if the input is suitable for casting according to said schema. In this case, for instance, the numeric <strong>string<\/strong> <strong>\u20181\u2019<\/strong> is cast to the <strong>number<\/strong> value <strong>1<\/strong>, because the schema asserts the <strong>id<\/strong> property must be a <strong>number<\/strong>. If an incompatible value, like a non-numeric <strong>string<\/strong>, was provided, or a required property was missing, an error would be thrown. So, if the method is successful, we can be sure <strong>newPizza<\/strong> is actually a <strong>Pizza<\/strong>, with <a href=\"https:\/\/www.typescriptlang.org\/docs\/handbook\/2\/everyday-types.html#type-assertions\">a little type assertion to make TypeScript happy<\/a>.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Let\u2019s add the third component next to the other ones\u2026<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-syntaxhighlighter-code\">\/\/ src\/pages\/PizzaWrapper.tsx\r\nimport React, {ReactElement} from 'react';\r\nimport PizzaWriter from '..\/components\/PizzaWriter';\r\nimport PizzaReader from '..\/components\/PizzaReader';\r\nimport PizzaTypedReader from '..\/components\/PizzaTypedReader';\r\n\r\nconst PizzaWrapper = (): ReactElement | null =&gt; {\r\n  return (\r\n    &lt;&gt;\r\n      &lt;PizzaWriter\/&gt;\r\n      &lt;PizzaReader\/&gt;\r\n      &lt;PizzaTypedReader\/&gt;\r\n    &lt;\/&gt;\r\n  );\r\n}\r\n\r\nexport default PizzaWrapper;\r\n<\/pre>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">\u2026and try again.<\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">Now we\u2019re talking! The <strong>new ID<\/strong> is a <strong>number<\/strong>, and the strict comparison returns <strong>true<\/strong>.<img decoding=\"async\" class=\"alignnone\" src=\"https:\/\/lh6.googleusercontent.com\/QVltGUH82zN_-390ogKivxb_OpRkwD3lHtS6nmLfl-aUa3Uln_LOAun7ANQxRnKYDyY4xtNvqvuIUGRynCh8_3lI9zJo9Y69dSwSyN_gEUxtwUhZVL_KAUTRyDVOF17pdnXPrZLPeCsb-U5dIen5flo\" alt=\"pizza writer pizza reader\" width=\"602\" height=\"649\" \/><\/p>\r\n\r\n\r\n\r\n<p class=\"wp-block-paragraph\">We can use Yup <strong>cast<\/strong> in any situation to make sure the values we get at runtime are actually typed like we expect in your code. Regardless of whether we have a scalar value, an object, or an array of objects, it doesn&#8217;t matter the complexity of the schema. This allows us to validate the structure of data retrieved from untrustworthy sources, like the <strong>localStorage<\/strong> , a query string or any storage that could be easily manipulated by a malicious user. Don\u2019t rely too much on it, though: this feature can only validate the type of your data, not the actual content, so stay alert. <a href=\"https:\/\/github.com\/Oimmei-Digital-Boutique\/react18-pizza-parsing-it\">the full project repository on Github<\/a>. As for me, I think I\u2019ll order a pizza.<\/p>\r\n","protected":false},"excerpt":{"rendered":"<p>While working on a project based on React, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source. There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s localStorage, a query string. For [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":25736,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"default","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[91],"tags":[],"class_list":["post-20793","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-software-development-en"],"acf":[],"aioseo_notices":[],"aioseo_head":"\n\t\t<!-- All in One SEO 5.0.1.1 - aioseo.com -->\n\t<meta name=\"description\" content=\"While working on a project based on React, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source. There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s localStorage, a query string. For\" \/>\n\t<meta name=\"robots\" content=\"max-image-preview:large\" \/>\n\t<meta name=\"author\" content=\"Oimmei Team\"\/>\n\t<meta name=\"google-site-verification\" content=\"nrov3ZDmFh2g122GMXaTWPiPrzv3uAspJFs_42s7-6s\" \/>\n\t<link rel=\"canonical\" href=\"https:\/\/www.oimmei.com\/en\/react-javascript-typed-object-parsing-with-yup-cast\/\" \/>\n\t<meta name=\"generator\" content=\"All in One SEO (AIOSEO) 5.0.1.1\" \/>\n\t\t<meta property=\"og:locale\" content=\"en_US\" \/>\n\t\t<meta property=\"og:site_name\" content=\"Oimmei Technologies | The Boutique Agency\" \/>\n\t\t<meta property=\"og:type\" content=\"article\" \/>\n\t\t<meta property=\"og:title\" content=\"Typed object parsing with Yup cast | Oimmei Technologies\" \/>\n\t\t<meta property=\"og:description\" content=\"While working on a project based on React, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source. There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s localStorage, a query string. For\" \/>\n\t\t<meta property=\"og:url\" content=\"https:\/\/www.oimmei.com\/en\/react-javascript-typed-object-parsing-with-yup-cast\/\" \/>\n\t\t<meta property=\"og:image\" content=\"https:\/\/www.oimmei.com\/wp-content\/uploads\/2026\/08\/oimmei-cover-website-26-scaled.png\" \/>\n\t\t<meta property=\"og:image:secure_url\" content=\"https:\/\/www.oimmei.com\/wp-content\/uploads\/2026\/08\/oimmei-cover-website-26-scaled.png\" \/>\n\t\t<meta property=\"article:published_time\" content=\"2023-08-22T09:12:53+00:00\" \/>\n\t\t<meta property=\"article:modified_time\" content=\"2025-07-29T09:05:49+00:00\" \/>\n\t\t<meta name=\"twitter:card\" content=\"summary\" \/>\n\t\t<meta name=\"twitter:title\" content=\"Typed object parsing with Yup cast | Oimmei Technologies\" \/>\n\t\t<meta name=\"twitter:description\" content=\"While working on a project based on React, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source. There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s localStorage, a query string. For\" \/>\n\t\t<meta name=\"twitter:image\" content=\"https:\/\/www.oimmei.com\/wp-content\/uploads\/2026\/08\/oimmei-cover-website-26-x.png\" \/>\n\t\t<!-- All in One SEO -->\n\n","aioseo_head_json":{"title":"Typed object parsing with Yup cast | Oimmei Technologies","description":"While working on a project based on React, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source. There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s localStorage, a query string. For","canonical_url":"https:\/\/www.oimmei.com\/en\/react-javascript-typed-object-parsing-with-yup-cast\/","robots":"max-image-preview:large","keywords":"","webmasterTools":{"google-site-verification":"nrov3ZDmFh2g122GMXaTWPiPrzv3uAspJFs_42s7-6s","miscellaneous":""},"schema":null,"og:locale":"en_US","og:site_name":"Oimmei Technologies | The Boutique Agency","og:type":"article","og:title":"Typed object parsing with Yup cast | Oimmei Technologies","og:description":"While working on a project based on React, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source. There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s localStorage, a query string. For","og:url":"https:\/\/www.oimmei.com\/en\/react-javascript-typed-object-parsing-with-yup-cast\/","og:image":"https:\/\/www.oimmei.com\/wp-content\/uploads\/2026\/08\/oimmei-cover-website-26-scaled.png","og:image:secure_url":"https:\/\/www.oimmei.com\/wp-content\/uploads\/2026\/08\/oimmei-cover-website-26-scaled.png","article:published_time":"2023-08-22T09:12:53+00:00","article:modified_time":"2025-07-29T09:05:49+00:00","twitter:card":"summary","twitter:title":"Typed object parsing with Yup cast | Oimmei Technologies","twitter:description":"While working on a project based on React, any framework using it, or even just plain JavaScript, it\u2019s not uncommon to have to fetch data from some external source. There are plenty of potential data sources you may use: web APIs, SDKs, documents from the file system, the browser window\u2019s localStorage, a query string. For","twitter:image":"https:\/\/www.oimmei.com\/wp-content\/uploads\/2026\/08\/oimmei-cover-website-26-x.png"},"aioseo_meta_data":{"post_id":"20793","title":null,"description":null,"keywords":null,"keyphrases":{"focus":{"keyphrase":"","score":0,"analysis":{"keyphraseInTitle":{"score":0,"maxScore":9,"error":1}}},"additional":[]},"primary_term":null,"canonical_url":null,"og_title":null,"og_description":null,"og_object_type":"default","og_image_type":"default","og_image_url":null,"og_image_width":null,"og_image_height":null,"og_image_custom_url":null,"og_image_custom_fields":null,"og_video":"","og_custom_url":null,"og_article_section":null,"og_article_tags":null,"twitter_use_og":false,"twitter_card":"default","twitter_image_type":"default","twitter_image_url":null,"twitter_image_custom_url":null,"twitter_image_custom_fields":null,"twitter_title":null,"twitter_description":null,"schema":{"blockGraphs":[],"customGraphs":[],"default":{"data":{"Article":[],"Course":[],"Dataset":[],"FAQPage":[],"Movie":[],"Person":[],"Product":[],"ProductReview":[],"Car":[],"Recipe":[],"Service":[],"SoftwareApplication":[],"WebPage":[]},"graphName":"BlogPosting","isEnabled":true},"graphs":[]},"schema_type":"default","schema_type_options":null,"pillar_content":false,"robots_default":true,"robots_noindex":false,"robots_noarchive":false,"robots_nosnippet":false,"robots_nofollow":false,"robots_noimageindex":false,"robots_noodp":false,"robots_notranslate":false,"robots_max_snippet":"-1","robots_max_videopreview":"-1","robots_max_imagepreview":"large","priority":null,"frequency":"default","local_seo":null,"breadcrumb_settings":null,"limit_modified_date":false,"ai":{"faqs":[],"keyPoints":[],"titles":[],"descriptions":[],"socialPosts":{"email":[],"linkedin":[],"twitter":[],"facebook":[],"instagram":[]}},"created":"2025-03-15 23:44:07","updated":"2025-07-29 09:06:40","seo_analyzer_scan_date":null,"focus_keyword":null,"additional_keywords":null,"truseo_locale":null},"aioseo_breadcrumb":"<div class=\"aioseo-breadcrumbs\"><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/www.oimmei.com\/en\/\" title=\"Home\">Home<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">|<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/www.oimmei.com\/en\/category\/software-development-en\/\" title=\"Software Development\">Software Development<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">|<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\tTyped object parsing with Yup cast\n\t\t<\/span><\/div>","aioseo_breadcrumb_json":[{"label":"Home","link":"https:\/\/www.oimmei.com\/en\/"},{"label":"Software Development","link":"https:\/\/www.oimmei.com\/en\/category\/software-development-en\/"},{"label":"Typed object parsing with Yup cast","link":"https:\/\/www.oimmei.com\/en\/react-javascript-typed-object-parsing-with-yup-cast\/"}],"_links":{"self":[{"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/posts\/20793","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/comments?post=20793"}],"version-history":[{"count":0,"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/posts\/20793\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/media\/25736"}],"wp:attachment":[{"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/media?parent=20793"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/categories?post=20793"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.oimmei.com\/en\/wp-json\/wp\/v2\/tags?post=20793"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}