<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Othmane Kahtal on Medium]]></title>
        <description><![CDATA[Stories by Othmane Kahtal on Medium]]></description>
        <link>https://medium.com/@othmanekahtal?source=rss-5d63410035fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bvdz6yPmbq1DJcmcb5kNvw.jpeg</url>
            <title>Stories by Othmane Kahtal on Medium</title>
            <link>https://medium.com/@othmanekahtal?source=rss-5d63410035fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:42:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@othmanekahtal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TypeScript for React Developers Series: Why You Should Adopt It]]></title>
            <link>https://medium.com/@othmanekahtal/typescript-for-react-developers-series-why-you-should-adopt-it-66f3742eddb7?source=rss-5d63410035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f3742eddb7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Othmane Kahtal]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 23:57:22 GMT</pubDate>
            <atom:updated>2024-09-12T23:57:22.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSBk5Gk4TZTKoweVxq9yZw.png" /></figure><p>TypeScript is a superset of JavaScript that adds static typing, which makes your code readable, maintainable and re-usable.</p><p>when you adopt TypeScript to React projects, you don’t need to add additional packages to validate props like prop-types, also you can catching types errors in compile-time rather than runtime, and getting IntelliSense to your IDE, which can help you to write code quickly and correctly.</p><h3>Prerequisites:</h3><ul><li>Basics of React.js</li></ul><p>The freedom of JavaScript can be painful when you work in a team, when you don’t write tests for your application, and when application grows.</p><p>Imagine you have a component that accepts ‘position’ as a prop, this prop will be ‘left’ or ‘right’ to work well, with JavaScript you need to add a manual check</p><pre>//components/MyComponent.jsx<br>function MyComponent({ position = &quot;left&quot; }) {<br>  if (position === &quot;left&quot;) {<br>    return &lt;div&gt;left&lt;/div&gt;;<br>  }<br>  if (position === &quot;right&quot;) {<br>    return &lt;div&gt;right&lt;/div&gt;;<br>  }<br>  return &lt;div&gt;position will be right or left&lt;/div&gt;;<br>}</pre><pre>//App.js<br>import MyComponent from &quot;./components/MyComponent&quot;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;MyComponent position=&quot;fddffd&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>you can use the prop-types to validate the props but it is still painful :</p><pre>//components/MyComponent.jsx<br>import React from &quot;react&quot;;<br>import PropTypes from &quot;prop-types&quot;;<br><br>function MyComponent({ position = &quot;left&quot; }) {<br>  if (position === &quot;left&quot;) {<br>    return &lt;div&gt;left&lt;/div&gt;;<br>  }<br>  if (position === &quot;right&quot;) {<br>    return &lt;div&gt;right&lt;/div&gt;;<br>  }<br>  return &lt;div&gt;position will be right or left&lt;/div&gt;;<br>}<br>MyComponent.propTypes = {<br>  position: PropTypes.oneOf([&quot;right&quot;, &quot;left&quot;]),<br>};<br>export default MyComponent;</pre><pre>//App.js<br>import MyComponent from &quot;./components/MyComponent&quot;;<br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;MyComponent position=&quot;fddffd&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>No warning or alert again 🥲:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*S6MSf1355g2730ha" /></figure><p>To make sure is props are valid you must open the console to show up the errors and warnings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nNVievkFD_FHOiz3" /></figure><p>But when we use TypeScript you will get alerts and warnings anywhere :</p><pre>//components/MyComponent.tsx<br>interface MyComponentProps {<br>  position: &quot;right&quot; | &quot;left&quot;;<br>}<br>function MyComponent({ position }: MyComponentProps) {<br>  return &lt;div&gt;{position}&lt;/div&gt;;<br>}<br>export default MyComponent;</pre><p>Your IDE tells you stop you have error 🛑</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0wDq2NgzxFdyTRH5" /></figure><p>Also your browser gives you alerts to correct your code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gMU7MZu5fNGYcG-3" /></figure><h3>conclusion:</h3><p>TypeScript is a powerful tool that helps you to become a productive developer and to write clean and readable code, it’s not just a props validator, we can do with it a lot of things like alias, creating solid and re-usable components with generics</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f3742eddb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript for React Developers Series: How to Get Started]]></title>
            <link>https://medium.com/@othmanekahtal/typescript-for-react-developers-series-how-to-get-started-3c668b4ad004?source=rss-5d63410035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c668b4ad004</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Othmane Kahtal]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 23:45:12 GMT</pubDate>
            <atom:updated>2024-09-12T23:49:16.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSBk5Gk4TZTKoweVxq9yZw.png" /></figure><p>By adopting TypeScript, React developers take advantage of the language’s type safety, code analysis, and refactoring capabilities. In this article, we’ll explore the steps needed to adopt TypeScript.</p><h3>Prerequisites:</h3><ul><li>Familiar with basic TypeScript types</li><li>Familiar with React.js</li><li>Reading the <a href="https://othmanekahtal.me/articles/adopting-typescript-for-react-developers-why">previous article</a></li></ul><h3>Naming Conventions:</h3><ul><li>use PascalCase for class, component and Enum names.</li><li>use camelCase for variable and function names.</li><li>do not use I as prefix of the interface instead use ComponentNameProps or FunctionNameParams.</li><li>use .generated.* as suffix for the files are generated and you don&#39;t edit them.</li></ul><pre>interface ComponentNameProps {<br>  position: &#39;left&#39; | &#39;right&#39;<br>}<br>function ComponentName({ position }: ComponentNameProps) {<br>  if (position === &#39;left&#39;) {<br>    return &lt;div&gt;left&lt;/div&gt;<br>  }<br>  return &lt;div&gt;right&lt;/div&gt;<br>}</pre><pre>interface FunctionNameParams {<br>  args: string[]<br>}<br>function functionName({ args }: FunctionNameParams) {<br>  return args.join(&#39; &#39;)<br>}</pre><h3>Types:</h3><ul><li>put the shared types in types.ts file.</li><li>use generics to avoid duplicating the components/functions.</li><li>do not export functions/types that not shared across multi-components.</li><li>in your component file, the type definitions must comes the first.</li><li>use <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html">Utility Types</a> to avoid duplicating of the type definitions.</li><li>use readonly to define the data coming from your API</li></ul><h3>Components:</h3><ul><li>don’t use FunctionComponent&lt;T&gt; or FC&lt;T&gt; to define your component, because it&#39;s explicit about the return type, while the normal function version is implicit, read more about this <a href="https://github.com/gndelia/codemod-replace-react-fc-typescript">codemod-replace-react-fc-typescript</a>.</li><li>use ReactNode instead JSX.Element to define your children when use the normal functions, because JSX.Element is the return value of React.createElement, while ReactNode is return value of a component</li><li>use generic components to make your component more flexible, <a href="https://www.developerway.com/posts/typescript-generics-for-react-developers">read more about this topic</a>.</li><li>use the React.ComponentPropsWithoutRef&lt;T&gt; as Wrapping/Mirroring a HTML Element when you want to make component that takes all the normal props of this Element.<a href="https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase">read more about this topic</a></li></ul><pre>// bad<br>interface MyCustomLinkProps {<br>  href: string<br>  children?: React.ReactNode<br>}<br>function MyCustomLink(props: MyCustomLinkProps) {<br>  const { children, href } = props<br>  return &lt;a href={href}&gt;{children}&lt;/a&gt;<br>}<br>// most recommended<br>function MyCustomLink(props: React.ComponentPropsWithoutRef&lt;&#39;a&#39;&gt;) {<br>  return &lt;a {...props}&gt;{children}&lt;/a&gt;<br>}</pre><ul><li>use Fragment or use the shorthand &lt;&gt; instead div in wrapping the component.</li></ul><pre>// bad<br>function ComponentName() {<br>  return (<br>    &lt;div&gt;<br>      &lt;section&gt;&lt;/section&gt;<br>      &lt;section&gt;&lt;/section&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>// most recommended<br>function ComponentName() {<br>  return (<br>    &lt;&gt;<br>      &lt;section&gt;&lt;/section&gt;<br>      &lt;section&gt;&lt;/section&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><h3>Forms and Events:</h3><ul><li>inline event handler:</li></ul><pre>const InputComponent = () =&gt; (<br>  &lt;input<br>    // TypeScript automatically inffers it<br>    onChange={(e) =&gt; {<br>      // logic here<br>    }}<br>  /&gt;<br>)</pre><ul><li>separated event handler:</li></ul><pre>const InputComponent = () =&gt; {<br>  const onChnageInputHandler = (e: React.FormEvent&lt;HTMLInputElement&gt;): void =&gt; {<br>    // your logic here<br>  }<br>  return &lt;input onChange={onChnageInputHandler} /&gt;<br>}</pre><p>or:</p><pre>const InputComponent = () =&gt; {<br>  const onChnageInputHandler: React.ChangeEventHandler&lt;HTMLInputElement&gt; = (<br>    e<br>  ) =&gt; {<br>    // your logic here<br>  }<br>  return &lt;input onChange={onChnageInputHandler} /&gt;<br>}</pre><ul><li>onSubmit definition for uncontrolled form component</li></ul><pre>const Form = () =&gt; (<br>  &lt;form<br>    onSubmit={(e: React.SyntheticEvent) =&gt; {<br>      e.preventDefault()<br>      const target = e.target as typeof e.target &amp; {<br>        email: { value: string }<br>        password: { value: string }<br>      }<br>      const email = target.email.value // typechecks!<br>      const password = target.password.value // typechecks!<br>      // etc...<br>    }}<br>  &gt;<br>    &lt;label&gt;<br>      Email:<br>      &lt;input type=&quot;email&quot; name=&quot;email&quot; /&gt;<br>    &lt;/label&gt;<br>    &lt;label&gt;<br>      Password:<br>      &lt;input type=&quot;password&quot; name=&quot;password&quot; /&gt;<br>    &lt;/label&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>  &lt;/form&gt;<br>)</pre><p>you can use formik or any other library for handling Forms, those libraries are built on the principles of controlled components</p><h3>Hooks:</h3><ul><li>useState hook :</li></ul><pre>const Component = () =&gt; {<br>  //1- inferred type:<br>  // `state` is inferred to be a number<br>  const [state, setState] = useState(0)<br>  // `stringState` is inferred to be a string<br>  const [stringState, setStringState] = useState(&#39;&#39;)<br>  //2- implicit type:<br>  const [state1, setState2] = useState&lt;number | undefined&gt;()<br>  return &lt;&gt;&lt;/&gt;<br>}</pre><ul><li>useCallback hook :</li></ul><pre>//   it&#39;s just like any other function<br>interface MemoizedFunctionParams {<br>params:string[]<br>}<br>const memoizedFunction = useCallback(<br>  (args:MemoizedFunctionParams) =&gt; {<br>    return &#39;text&#39;<br>  },<br>  [...],<br>);</pre><ul><li>useReducer hook:</li></ul><pre>import { useReducer } from &#39;react&#39;<br><br>const initialState = { count: 0 }<br>type ACTIONTYPE =<br>  | { type: &#39;increment&#39;; payload: number }<br>  | { type: &#39;decrement&#39;; payload: string }<br>function reducer(state: typeof initialState, action: ACTIONTYPE) {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { count: state.count + action.payload }<br>    case &#39;decrement&#39;:<br>      return { count: state.count - Number(action.payload) }<br>    default:<br>      throw new Error()<br>  }<br>}<br>function Counter() {<br>  // If you don&#39;t define return type, TypeScript automatically infers it.<br>  const [state, dispatch] = useReducer(reducer, initialState)<br>  return (<br>    &lt;&gt;<br>      Count: {state.count}<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39;, payload: &#39;5&#39; })}&gt;<br>        -<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39;, payload: 5 })}&gt;<br>        +<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><ul><li>useRef hook :</li></ul><pre>import { useRef, useEffect } from &#39;react&#39;<br>// This is just an example, React recommended you to use Controlled components<br>function Component() {<br>  const inputRef = useRef&lt;HTMLInputElement&gt;(null)<br>  const divRef = useRef&lt;HTMLDivElement&gt;(null)<br>  useEffect(() =&gt; {<br>      if (!inputRef) {<br>        throw Error(&#39;input not mounted !!!!&#39;)<br>      }<br>      inputRef.current.value = &#39;assign value&#39;<br>    }, [])<br>    const onChnageButtonHandler = () =&gt; {<br>      divRef.current.innerHTML = &#39;we change this text here&#39;<br>    }<br>  return (<br>    &lt;div&gt;<br>      &lt;input ref={inputRef} /&gt;<br>      &lt;div ref={divRef}&gt;this is div content&lt;/div&gt;<br>      &lt;button onClick={onChnageButtonHandler}&gt;change the content&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Context:</h3><ul><li>with default value:</li></ul><pre>import { createContext, useState, useContext } from &#39;react&#39;<br><br>type ThemeContextType = &#39;light&#39; | &#39;dark&#39;<br>const ThemeContext = createContext&lt;ThemeContextType&gt;(&#39;light&#39;)<br>const App = () =&gt; {<br>  const [theme, setTheme] = useState&lt;ThemeContextType&gt;(&#39;light&#39;)<br>  return (<br>    &lt;ThemeContext.Provider value={theme}&gt;<br>      &lt;MyComponent /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  )<br>}<br>const MyComponent = () =&gt; {<br>  const theme = useContext(ThemeContext)<br>  return &lt;p&gt;The current theme is {theme}.&lt;/p&gt;<br>}</pre><ul><li>without default value:</li></ul><pre>import { createContext, useState, useContext } from &#39;react&#39;<br><br>type userContextType = { name: string; email: string }<br>const UserContext = createContext&lt;userContextType&gt;()<br>const App = () =&gt; {<br>  const [user, setUser] = useState&lt;userContextType&gt;({<br>    name: &#39;name&#39;,<br>    email: &#39;email@mail.com&#39;,<br>  })<br>  return (<br>    &lt;ThemeContext.Provider value={...{ user, setUser }}&gt;<br>      &lt;MyComponent /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  )<br>}<br>const MyComponent = () =&gt; {<br>  const { user } = useContext(UserContext)<br>  return &lt;p&gt;The current theme is {user?.name}.&lt;/p&gt;<br>}</pre><h3>Conclusion:</h3><p>In conclusion, using TypeScript with React can write safer, more maintainable code, and catch errors earlier in the development process. Additionally, TypeScript’s static typing can help improve developer productivity by providing better tooling and documentation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c668b4ad004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adopting TypeScript for React: Practical Tips and Real-World Scenarios]]></title>
            <link>https://medium.com/@othmanekahtal/adopting-typescript-for-react-practical-tips-and-real-world-scenarios-452d2fa76f65?source=rss-5d63410035fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/452d2fa76f65</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Othmane Kahtal]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 23:53:14 GMT</pubDate>
            <atom:updated>2024-09-12T23:51:05.766Z</atom:updated>
            <content:encoded><![CDATA[<h3>TypeScript for React Developers Series: Practical Tips and Real-World Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eSBk5Gk4TZTKoweVxq9yZw.png" /></figure><p>Switching to TypeScript can significantly enhance your React development experience by making your code more maintainable and scalable. With TypeScript’s powerful type-checking, you’ll catch bugs early, enjoy better code navigation, and find refactoring easier. In this article, we’ll dive into practical tips and real-world scenarios to help you effectively adopt TypeScript in your React projects. Whether you’re new to TypeScript or looking to refine your skills, this guide has something for you. Let’s get started!</p><h3>Prerequisites:</h3><ul><li>Familiarity with basic TypeScript types</li><li>Familiarity with React.js</li><li>Reading the <a href="https://othmanekahtal.me/articles/typescript-react-why-adopt"><strong>previous article</strong></a> is recommended</li></ul><p>TypeScript provides several built-in utilities that help reduce type duplication, making your code cleaner and easier to maintain. Let’s explore some of these utilities and see how they can be applied in real-world scenarios.</p><h3>For Objects:</h3><p>TypeScript provides utilities to avoid duplicating type definitions for objects. Let’s start with a basic object and apply some of these utilities!</p><pre>type User = {<br>  email: string;<br>  first_name: string;<br>  last_name: string;<br>  username: string;<br>}</pre><h4>Pick vs. Omit:</h4><p>Sometimes, we need to create a type similar to an existing one but with some properties added or removed. TypeScript provides the Omit and Pick utilities to make this easy:</p><pre>type User = {<br>  email: string;<br>  first_name: string;<br>  last_name: string;<br>  username: string;<br>}<br><br>// Create new type without email and username:<br>type UserWithoutEmailUsername = Omit&lt;User, &#39;email&#39; | &#39;username&#39;&gt;<br>// Result:<br>// type UserWithoutEmailUsername = {<br>//   last_name: string;<br>//   first_name: string;<br>// }</pre><p>In this example, we use Omit to exclude email and username from the User type.</p><pre>type User = {<br>  email: string;<br>  first_name: string;<br>  last_name: string;<br>  username: string;<br>}<br><br>// Create new type with only email and username:<br>type UserWithEmailUsername = Pick&lt;User, &#39;email&#39; | &#39;username&#39;&gt;<br>// Result:<br>// type UserWithEmailUsername = {<br>//   email: string;<br>//   username: string;<br>// }</pre><p>Here, we use Pick to include only email and username from the User type.</p><p>So, when should you use Pick or Omit? It depends on the type you want to manipulate and how you want to modify it.</p><h4>Required vs. Partial:</h4><p>Let’s consider a real scenario: you’re building an API application with endpoints for creating and updating resources. You need different types for each service function. Your code might look like this:</p><pre>type User = {<br>    email: string;<br>    first_name: string;<br>    last_name: string;<br>    username: string;<br>}<br><br>function createUser(user: User) {<br>    // ....<br>    return {<br>        email: user.email,<br>        username: user.username,<br>        id: 10<br>    }<br>}<br>type OptionalUser = {<br>    email?: string;<br>    first_name?: string;<br>    last_name?: string;<br>    username?: string;<br>}<br>// You need an ID to query the user that you want to update<br>function updateUser(user: OptionalUser, id: number) {<br>    // ....<br>    return {<br>        email: user.email,<br>        username: user.username,<br>        id: 10<br>    }<br>}</pre><p>But you can simplify this using Partial, making your code cleaner:</p><pre>type User = {<br>    email: string;<br>    first_name: string;<br>    last_name: string;<br>    username: string;<br>}<br><br>function createUser(user: User) {<br>    // ....<br>    return {<br>        email: user.email,<br>        username: user.username,<br>        id: 10<br>    }<br>}<br>function updateUser(user: Partial&lt;User&gt;, id: number) {<br>    // ....<br>    return {<br>        email: user?.email,<br>        username: user?.username,<br>        id: 10<br>    }<br>}</pre><p>This makes your code easier to understand and more consistent.</p><p>What if you have a type with optional properties, and you want to clone this type but make all properties required? TypeScript provides the Required utility:</p><pre>type OptionalUser = {<br>    email?: string;<br>    first_name?: string;<br>    last_name?: string;<br>    username: string;<br>}</pre><pre>type RequiredUser = Required&lt;OptionalUser&gt;</pre><h4>Readonly:</h4><p>When working with React, the props passed to a component shouldn’t be modified within the component to enforce immutability. TypeScript provides the readonly modifier to prevent reassignment of props, supporting this best practice. <a href="https://rules.sonarsource.com/typescript/RSPEC-6759/">React props should be read-only</a>.</p><pre>import React from &#39;react&#39;;</pre><pre>// Define the props interface with readonly<br>interface UserCardProps {<br>  readonly name: string;<br>  readonly age: number;<br>}</pre><pre>const UserCard: React.FC&lt;UserCardProps&gt; = ({ name, age }) =&gt; {<br>  // Attempting to modify name or age will cause a TypeScript error<br>  // name = &quot;New Name&quot;; // Error: Cannot assign to &#39;name&#39; because it is a read-only property.</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{name}&lt;/h2&gt;<br>      &lt;p&gt;Age: {age}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default UserCard;</pre><h4>Record:</h4><p>The Record utility is a powerful tool to create objects with specific key-value pairs, ensuring that all keys are present and that each key&#39;s value matches a defined type. Let&#39;s consider a real-world scenario where using the Record utility type would be beneficial. Imagine you are developing an admin dashboard for a web application where users have different roles, such as admin, editor, and viewer. Each role has specific permissions associated with it, such as the ability to create, read, update, or delete data. You can use the Record type to define and manage these roles and their permissions in a type-safe way.</p><p><strong>Define User Roles and Permissions:</strong></p><pre>// Define possible roles<br>type UserRole = &#39;admin&#39; | &#39;editor&#39; | &#39;viewer&#39;;<br><br>// Define possible permissions<br>type Permission = &#39;create&#39; | &#39;read&#39; | &#39;update&#39; | &#39;delete&#39;;<br>// Use Record to map roles to their permissions<br>const rolePermissions: Record&lt;UserRole, Permission[]&gt; = {<br>  admin: [&#39;create&#39;, &#39;read&#39;, &#39;update&#39;, &#39;delete&#39;],<br>  editor: [&#39;create&#39;, &#39;read&#39;, &#39;update&#39;],<br>  viewer: [&#39;read&#39;],<br>};</pre><p><strong>Creating a Function to Check Permissions:</strong></p><pre>function hasPermission(role: UserRole, permission: Permission): boolean {<br>  const permissions = rolePermissions[role];<br>  return permissions.includes(permission);<br>}</pre><p><strong>Using the Function in a Component:</strong></p><pre>import React from &#39;react&#39;;<br>type UserProps = {<br>  role: UserRole;<br>};<br>const Dashboard: React.FC&lt;UserProps&gt; = ({ role }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Dashboard&lt;/h1&gt;<br>      {hasPermission(role, &#39;create&#39;) &amp;&amp; (<br>        &lt;button&gt;Create New Item&lt;/button&gt;<br>      )}<br>      {hasPermission(role, &#39;read&#39;) &amp;&amp; (<br>        &lt;div&gt;Here are the items you can view.&lt;/div&gt;<br>      )}<br>      {hasPermission(role, &#39;update&#39;) &amp;&amp; (<br>        &lt;button&gt;Update Item&lt;/button&gt;<br>      )}<br>      {hasPermission(role, &#39;delete&#39;) &amp;&amp; (<br>        &lt;button&gt;Delete Item&lt;/button&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br>export default Dashboard;</pre><p><strong>Example Usage of the Dashboard Component:</strong></p><pre>import React from &#39;react&#39;;<br>import Dashboard from &#39;./Dashboard&#39;;<br><br>const App: React.FC = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Admin View&lt;/h1&gt;<br>      &lt;Dashboard role=&quot;admin&quot; /&gt;<br>      &lt;h1&gt;Editor View&lt;/h1&gt;<br>      &lt;Dashboard role=&quot;editor&quot; /&gt;<br>      &lt;h1&gt;Viewer View&lt;/h1&gt;<br>      &lt;Dashboard role=&quot;viewer&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default App;</pre><h4>NonNullable</h4><p>Let’s consider a scenario where you have a form for managing user profiles. This form can be used to create a new user or edit an existing one. We’ll use TypeScript to handle these scenarios safely, ensuring that certain fields are non-nullable when the form is submitted.</p><p><strong>Defining the User Data Type:</strong></p><pre>interface User {<br>  id?: number; // Optional during creation, required during editing<br>  username: string;<br>  email: string;<br>  age?: number;<br>}</pre><p><strong>Form State Type:</strong></p><pre>type UserFormState = {<br>  id?: number;<br>  username: string | undefined;<br>  email: string | undefined;<br>  age?: number | undefined;<br>};</pre><p>This type allows fields like username and email to be undefined initially, especially when editing.</p><p><strong>Using </strong><strong>NonNullable to Ensure Non-Nullable Fields</strong></p><p>When submitting the form, you want to make sure that username and email are always defined:</p><pre>type ValidUser = Omit&lt;User, &#39;id&#39;&gt; &amp; {<br>  id?: number;<br>  username: NonNullable&lt;UserFormState[&#39;username&#39;]&gt;;<br>  email: NonNullable&lt;UserFormState[&#39;email&#39;]&gt;;<br>};</pre><p>Here, ValidUser ensures that username and email are non-nullable, making sure</p><p>these fields are always present when processing the form submission.</p><p><strong>Form Component Implementation:</strong></p><pre>import React, { useState } from &#39;react&#39;;<br><br>const UserForm: React.FC&lt;{ initialData?: User }&gt; = ({ initialData }) =&gt; {<br>  // Initialize form state with optional initial data<br>  const [formState, setFormState] = useState&lt;UserFormState&gt;({<br>    id: initialData?.id,<br>    username: initialData?.username,<br>    email: initialData?.email,<br>    age: initialData?.age,<br>  });<br>  const handleChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const { name, value } = event.target;<br>    setFormState((prevState) =&gt; ({ ...prevState, [name]: value }));<br>  };<br>  const handleSubmit = () =&gt; {<br>    // Assert that username and email are non-nullable<br>    const { id, username, email, age } = formState;<br>    if (!username || !email) {<br>      alert(&#39;Username and email are required.&#39;);<br>      return;<br>    }<br>    const validUser: ValidUser = {<br>      id,<br>      username,<br>      email,<br>      age,<br>    };<br>    // Proceed with form submission logic<br>    console.log(&#39;Submitting form:&#39;, validUser);<br>  };<br>  return (<br>    &lt;form onSubmit={(e) =&gt; e.preventDefault()}&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;<br>          Username:<br>          &lt;input<br>            type=&quot;text&quot;<br>            name=&quot;username&quot;<br>            value={formState.username || &#39;&#39;}<br>            onChange={handleChange}<br>            required<br>          /&gt;<br>        &lt;/label&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;<br>          Email:<br>          &lt;input<br>            type=&quot;email&quot;<br>            name=&quot;email&quot;<br>            value={formState.email || &#39;&#39;}<br>            onChange={handleChange}<br>            required<br>          /&gt;<br>        &lt;/label&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;label&gt;<br>          Age:<br>          &lt;input<br>            type=&quot;number&quot;<br>            name=&quot;age&quot;<br>            value={formState.age || &#39;&#39;}<br>            onChange={handleChange}<br>          /&gt;<br>        &lt;/label&gt;<br>      &lt;/div&gt;<br>      &lt;button type=&quot;submit&quot; onClick={handleSubmit}&gt;<br>        Submit<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br>export default UserForm;</pre><h3>For Functions:</h3><p>TypeScript gives us many utilities to work with functions, allowing us to infer types and avoid duplicating type definitions. Let’s dive into an example:</p><pre>type User = {<br>  email: string;<br>  first_name: string;<br>  last_name: string;<br>  username: string;<br>}<br><br>function createUser(args: User) {<br>    // ....<br>    return {<br>        id: 12,<br>        email: args.email,<br>        username: args.username<br>    }<br>}</pre><p><strong>How can we infer the return type of this function?</strong></p><p>We have two methods to get the return type of this function:</p><pre>type returnTypeOfCreateUser = Omit&lt;User, &#39;last_name&#39; | &#39;first_name&#39;&gt;</pre><p>This approach works, but it doesn’t offer the flexibility or consistency needed if the return type of the function changes. To solve this, we can use ReturnType to directly infer the type:</p><pre>type returnTypeOfCreateUser2 = ReturnType&lt;typeof createUser&gt;</pre><p><strong>What about async functions?</strong></p><pre>async function createUser2(args: User) {<br>    // ....<br>    return {<br>        id: 12,<br>        email: args.email,<br>        username: args.username<br>    }<br>}</pre><p>The answer is yes! You can combine Awaited with ReturnType to handle async functions:</p><pre>type returnTypeOfCreateUser3 = Awaited&lt;ReturnType&lt;typeof createUser2&gt;&gt;</pre><p><strong>What if I want to get the type of parameters that a function from an external library accepts?</strong></p><p>Imagine you’re using a third-party library, and you want to wrap one of its functions. You can use the Parameters utility to get the types of its parameters:</p><pre>type paramsType = Parameters&lt;typeof createUser&gt; // type paramsType = [args: User]</pre><p>The Parameters utility returns an array of the parameter types that createUser accepts!</p><h3>Conclusion</h3><p>TypeScript’s utility types like ReturnType, Parameters, Partial, Required, Omit, Pick, Readonly, Record, and NonNullable make it easier to write clean, maintainable, and type-safe React code. By using these utilities, you can handle real-world scenarios effectively, reduce errors, and enhance the overall quality of your projects. Start leveraging these powerful features to take your React development to the next level. For more detailed information and advanced use cases, check out additional resources like the <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html">TypeScript Handbook</a> and the <a href="https://react.dev/reference/react">React Documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=452d2fa76f65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>