How to deal with react router url params and type script

Viewed 272

In react router, I am going through the tutorial but trying to use typescript and have this code

let params = useParams();
let id:string = params.invoiceId
let invoice = getInvoice(parseInt(id, 10));

The second line has an error

TS2322: Type 'string | undefined' is not assignable to type 'string'.   Type 'undefined' is not assignable to type 'string'

How do I do this properly to lookup and display the invoice? Also, how to reroute to the catch all * if the string is not an integer.

thanks, Dean

1 Answers

How do I do this properly to lookup and display the invoice?

The invoiceId route param is potentially undefined and typed as "string | undefined" so your id type should match.

const params = useParams();
const id: string | undefined = params.invoiceId;

Since id is now also potentially undefined, and the parseInt expects a string type you can either:

  1. Use a guard-clause:

    const invoice = id && getInvoice(parseInt(id, 10));
    
  2. Or use the Number constructor which takes an optional any type:

    const invoice = getInvoice(Number(id));
    

Also, how to reroute to the catch all * if the string is not an integer.

If you want to check/test the id parameter first to ensure it is a integer you can use a regular expression to test for only number characters and issue an imperative redirect.

Example:

const navigate = useNavigate();

...

useEffect(() => {
  if (id && /[^\d]/g.test(id)) {
    navigate("/", { replace: true });
  }
}, [id, navigate]);

Edit how-to-deal-with-react-router-url-params-and-type-script

Related