简体   繁体   中英

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 string | string[] | undefined 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM