简体   繁体   English

如何在 TypeScript 中键入解构的 object 密钥

[英]How to type destructured object key in TypeScript

Let's say I have query parameter from router in Next.js假设我在 Next.js 中有来自路由器的查询参数

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

This { id } is string | string[] | undefined这个{ id }string | string[] | undefined 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.我需要将它作为参数传递给另一个 function,并且我知道当我在需要id的地方执行 function 时它将是一个string

How can I make id as string in destructuring?如何在解构中将id as string

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 TS Playground 中的代码


However, it's safer not to assume and assert, but to actually check at runtime:但是,更安全的做法是不要假设和断言,而是在运行时实际检查:

TS Playground TS游乐场

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另请参阅:TS 手册中的使用类型谓词

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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