Home > Net >  Type 'unknown' is not assignable to type in Typescript
Type 'unknown' is not assignable to type in Typescript

Time:07-07

Please help me out below is my code. I want to be get rid of the error

import { useLocation } from "react-router-dom";

interface userState {
  status: string;
  id: string;
}

export default function Details() {
  const location = useLocation();
  const user: userState = location.state;
  console.log(user.id);
}

enter image description here

CodePudding user response:

You can avoid that warning by using type assertions in typescript as follows only if it's really necessary.

const user: userState = location.state as userState;

CodePudding user response:

Overriding the type of useLocation.state might be more useful for future use.

import { Location, useLocation } from "react-router-dom";

interface userState {
  status: string;
  id: string;
}

interface UseLocation extends Location {
  state: userState;
}

// do not use *.d.ts for this declaration.
// just declare it in any *.ts file.
// this declaration is effective in other components as well.

declare module "react-router-dom" {
  export function useLocation(): UseLocation;
}

export function Details() {
  const location = useLocation();

  const user: userState = location.state;
  console.log(user.id);
}

  • Related