typescripttsx

Type 'x' is not assignable to type never error after I return from a function


I am new to typescript and I already hate it, I use React js and I tried to do something super simple, here is the code:

 const nav = useRef(null);

  function toggleNavbar() {
    const navbar: object | null = nav.current;
    if (!navbar) return;

    navbar["style"]["transform"] = "translate(0)";
  }

I get the error type string is not assignable to type never after I conditionally return. navbar["style"]["transform"] = "translate(0)"; here the navbar is of type never. How to fix that? I already defined a type for it


Solution

  • Don't use object

    object is a super vague type.

    object['style'] can be anything, including null, undefined, etc.

    The TypeScript compiler can't know that object['style'] is something that can have a transform property.

    Don't use object. Use the actual type.

    Define the type when you create the reference

    Don't define the type here: const navbar: object | null = nav.current;

    Define it here:

    const nav = useRef<HTMLElement>(null);
    

    BUT!!! Don't use references when you don't have to.

    Direct DOM access is sometimes useful in React, but is usually more trouble than it is worth. React is designed to manage your DOM for you.

    Focus on your data instead.

    const MyComponent = () => {
         const [isOpen, setIsOpen] = useState(false);
    
         return (<div>
             <button type="button" onClick={() => setIsOpen(prev => !prev)}>
                 Toggle
             </button>
             <nav style={{ transform: isOpen ? "translate(0)" : "" }}>...</nav>
         </div>);
    }