Home > Back-end >  How to type destructured object key in TypeScript
How to type destructured object key in TypeScript

Time:12-06

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.

How can I make id as string in destructuring?

CodePudding user response:

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

  • Related