Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to type destructured object key in TypeScript

Let’s say I have query parameter from router in Next.js

const {
    query: { id },
  } = useRouter();

This { id } is string | string[] | undefined.

I need to pass it as parameter to another function, and I know that it will be a string when I will execute a function where id is needed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I make id as string in destructuring?

>Solution :

It seems that the question is "How can I use a type assertion with a destructuring assignment?"

If that’s right, then you must use the assertion after the right-side expression value. Using the code in your question:

What you currently have:

import { useRouter, type NextRouter } from 'next/router';

const { query: { id } } = useRouter();
               //^? const id: string | string[] | undefined

How to use the type assertion:

import { useRouter, type NextRouter } from 'next/router';

const { query: { id } } = useRouter() as NextRouter & { query: { id: string } };
               //^? const id: string

Code in TS Playground


However, it’s safer not to assume and assert, but to actually check at runtime:

TS Playground

import { useRouter } from 'next/router';

const { query: { id } } = useRouter();
               //^? const id: string | string[] | undefined

if (typeof id === 'string') {
  // Now you can be confident that it's really a string.
  // Do things with the string here.
  id;
//^? const id: string
}
else {
  // It's either an array or undefined.
  // Handle that case here.
  id;
//^? const id: string[] | undefined
}

See also: Using type predicates in the TS handbook

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading