簡體   English   中英

如何在 TypeScript 中鍵入解構的 object 密鑰

[英]How to type destructured object key in TypeScript

假設我在 Next.js 中有來自路由器的查詢參數

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

這個{ id }string | string[] | undefined string | string[] | undefined string | string[] | undefined

我需要將它作為參數傳遞給另一個 function,並且我知道當我在需要id的地方執行 function 時它將是一個string

如何在解構中將id as string

問題似乎是“我怎樣才能將類型斷言解構分配一起使用?”

如果那是正確的,那么您必須在右側表達式值之后使用斷言。 使用您問題中的代碼:

你目前擁有的:

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

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

如何使用類型斷言:

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

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

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
}

另請參閱:TS 手冊中的使用類型謂詞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM