[英]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
但是,更安全的做法是不要假設和斷言,而是在運行時實際檢查:
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.